GeekInterview.com
  I am new, Sign me up!
 
GeekInterview.com  >  Interview Questions  >  Programming  >  C++
Go To First  |  Previous Question  |  Next Question 
 C++  |  Question 93 of 203    Print  
What happens to the member pointers when an exception occures in constructor, while allocating memory ? how can we over come this ?

  
Total Answers and Comments: 2 Last Update: May 21, 2007     Asked by: Shyam 
  
 Sponsored Links

 
 Best Rated Answer
Submitted by: mohit12379
 

Offcourse it will result memory leak.... so use auto_ptr for such thing .. see following example, i have used two types to avoid memory leaks one is auto_ptr and another is initialize function

#include <iostream>

#include <memory>

class DataClass{

public:

int m_iValue;

DataClass(int i =0):m_iValue(i){}

void show(void) {

std::cout<<std::endl<<"Value :- "<<m_iValue<<std::endl;

}

};

class ResourceLeakFreeClass{

public:

std::auto_ptr<DataClass> m_Data1;

DataClass * m_Data2;

ResourceLeakFreeClass():m_Data1(new DataClass(100)),m_Data2(InitDataClass(200)){}

~ResourceLeakFreeClass(){

if(m_Data2){

delete m_Data2;

m_Data2 = 0;

}

}

DataClass * InitDataClass(int iData){

try{return new DataClass(iData);}

catch (...) {delete m_Data2;throw;}

}

};

int main(int argc, char* argv[])

{

ResourceLeakFreeClass RLFC;

RLFC.m_Data1->show();

RLFC.m_Data2->show();

return 0;

}



Above answer was rated as good by the following members:
yzesong
July 28, 2006 15:30:58   #1  
mohit12379 Member Since: March 2006   Contribution: 17    

RE: What happens to the member pointers when an except...

Offcourse it will result memory leak.... so use auto_ptr for such thing .. see following example i have used two types to avoid memory leaks one is auto_ptr and another is initialize function

#include <iostream>

#include <memory>

class DataClass{

public:

int m_iValue;

DataClass(int i 0):m_iValue(i){}

void show(void) {

std::cout<<std::endl<< Value :- <<m_iValue<<std::endl;

}

};

class ResourceLeakFreeClass{

public:

std::auto_ptr<DataClass> m_Data1;

DataClass * m_Data2;

ResourceLeakFreeClass():m_Data1(new DataClass(100)) m_Data2(InitDataClass(200)){}

~ResourceLeakFreeClass(){

if(m_Data2){

delete m_Data2;

m_Data2 0;

}

}

DataClass * InitDataClass(int iData){

try{return new DataClass(iData);}

catch (...) {delete m_Data2;throw;}

}

};

int main(int argc char* argv[])

{

ResourceLeakFreeClass RLFC;

RLFC.m_Data1->show();

RLFC.m_Data2->show();

return 0;

}


 
Is this answer useful? Yes | NoAnswer is useful 1   Answer is not useful 0Overall Rating: +1    
May 21, 2007 23:34:57   #2  
heyjoe Member Since: May 2007   Contribution: 2    

RE: What happens to the member pointers when an except...
When a constructor throws an exception then it means that constructor failed (duh!!) and the object is never created.

Just write a simple class to test it out yourself.

 
Is this answer useful? Yes | NoAnswer is useful 0   Answer is not useful 1Overall Rating: -1    

 Related Questions

Ø      Public, protected and private are three access specifiers in C++.  Ø      Public data members and member functions are accessible 
Latest Answer : Private Protected and Public all these are access specifiers.Private Data Members are only available inside classProtected Data Members are  only available inside class as well as in derived classes.Public Data members are available ...

As the name suggests, the function acts as a friend to a class. As a friend of a class, it can access its private and protected members. A friend function is not a member of the class. But it must be 
Latest Answer : Friend function is used in OOP languages which allows a private or protected function to be accessed by a member outside a class. Any function outside a Class can be given access to work with members inside a class by simply writing a keyword friend ...

A scope resolution operator (::), can be used to define the member functions of a class outside the class.  
Latest Answer : Scope resolution:As the name itself indicates,it resolves global scope to local scopeEx:int a=10;int main(){a=20;cout

The free subroutine frees a block of memory previously allocated by the malloc subroutine. Undefined results occur if the Pointer parameter is not a valid pointer. If the Pointer parameter is a null value, 
Latest Answer : free() - releases the memory of the pointer passed as parameter, to the OS/application consumption. Using the pointer after free() will result in undefinded resultsrealloc() - used to resize the memory held by the pointer to the number of bytes specificed. ...

A pure virtual member function is a member function that the base class forces derived classes to provide. Normally these member functions have no implementation. Pure virtual functions are equated to 
Latest Answer : Pure virtual function is the virtual functions which member functions does not have any definitions(implementation),just it equates(=) to 0. With Pure virtual function, the base class becomes "Abstract class". The abstract class does not instantiate/ ...

Virtual destructors: If an object (with a non-virtual destructor) is destroyed explicitly by applying the delete operator to a base-class pointer to the object, the base-class destructor function (matching 
Latest Answer : Virtual constructor is not build-in C++ feature but it doesn't mean its not used by devs in code and in conversations. There are many other things that doesn't exist in particular language yet, people find ways around to solve it (SingleTon, Virtual Constructor, ...

Latest Answer : A constructor of a class is mainly responsibly for turning the raw memory allotted to an object into a usable object. DEFAULT CONSTRUCTOR:The default constructor is a constructor that takes no argument. Part::Part()String() and String(const char* str) ...
Read Answers (7) | Asked by : anil_mca

Latest Answer : Inspite of repeated requests by some (few) sensible people to everybody to read the question properly before responding, nobody listens.For doreen, the question does not ask you to explain deep copy and shallow copy mechanism neither does is asks how ...
Read Answers (3) | Asked by : suji

No 
Latest Answer : yes in c++ a class can have a default constructor.a default constructor is  a constructor which doesn't pass any arguements to it. ...
Read Answers (6) | Asked by : Nisar.E

Latest Answer : Memory leak is - dynamically allocating memory and forgeting to free it. In C++, using a new operator to allocate a chunk of memory, and forgetting to delete it. There are several reasons this could occur. Some of them are,1. Allocate a chunk of memory ...
Read Answers (4) | Asked by : gopala krishna


 Sponsored Links

 
Related Articles

Concepts of Object-Oriented Programming

Object Oriented JavaScript In this chapter you ll learn about OOP Object Oriented Programming and how it relates to JavaScript As an ASP NET developer you probably have some experience working with objects and you may even be familiar with concepts such as inheritance However unless you re already a
 

C++ Memory Management operators

C Memory Management operators Need for Memory Management operators The concept of arrays has a block of memory reserved The disadvantage with the concept of arrays is that the programmer must know while programming the size of memory to be allocated in addition to the array size remaining constant m
 

C++ Pointers

C Pointers Concept of Pointers Every storage location of memory has an associated address Address is a number that grows sequentially For every program placed in memory each variable or function in the program has an associated address mosgoogle center The address of operator The address of operator
 

SQL Programming

SQL Programming Overview Anybody who has done something for a long time has probably wanted to change how things work at some point or another. A worker at a mill might have found a more efficient way of cutting logs, or a mathematics teacher might have had a hand in changing a school&rsquo;s al
 

The Interview Snafu

How to turn someone else&rsquo;s mistake to your advantage Your dream job is about to become reality. A recruiter gave you the heads up about the perfect position at Humungous Conglomerate, Inc. You went through five interviews as well as a battery of psychological tests mandated by their HR de
 

Winning a Job Interview with a Winning Resume

Does your resume unlock your potential, take your skills to the highest level and win you the interview and the job you want now? The job market today is highly competitive and even if you think you have what it takes to get an interview you won&rsquo;t get over the line without a polished, prof
 

WinRunner Programming Concepts

If you want to create WinRunner scripts that are highly efficient, there are important programming concepts that you will want to become familiar with. Understanding these concepts will provide you with a large number of key benefits. In addition to understanding these concepts, you must also learn
 

Programming Languages Certification

IT Certification programs have several options that will offer you the best knowledge.&nbsp; By learning everything that you need to know about information technology you will be able to open new doors to your career and personal business desires.&nbsp; IT Certification offers several vari
 

JavaScript Exception Handling – Part II

JavaScript Exception Handling Part II In this JavaScript tutorial you will learn about exception handling viz try&hellip; catch finally statement and nested try&hellip; catch statements along with syntax and examples mosgoogle center try&hellip; catch finally Statement JavaScript has a
 

JavaScript Exception Handling – Part I

JavaScript Exception Handling Part I In this JavaScript tutorial you will learn about Exception Handling Catching errors in JavaScript Using try catch statement and throw in JavaScript along with syntax and examples mosgoogle center It is impossible for a programmer to write a program without erro
 

About Us -  Privacy Policy -  Terms and Conditions -  Contact -  Ask Question -  Propose Category -  Site Updates 

Copyright © 2005 - 2009 GeekInterview.com. All Rights Reserved

Page copy protected against web site content infringement by Copyscape