CoolInterview.com - World's Largest Collection of Interview Questions
Send Free SMS
 Interview Questions  
 Our Services  


INTERVIEW QUESTIONS LANGUAGES C++ DETAILS
Question :
What happens to the member pointers when an exception occurs in constructor, while allocating memory?How can we over come this ?


Category C++ Interview Questions
Rating (3.0) By 1 users
Added on 8/18/2006
Views 3039
Rate it!
Answers:

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;

}



Constructor can't throw Exceptions.



 Posted by: jitendra singh    

Contact jitendra singh  Contact jitendra singh


If you have the better answer, then send it to us. We will display your answer after the approval.
Name :*
Email Id :*
Answer :*
Verification Code Code Image - Please contact webmaster if you have problems seeing this image code Not readable? Load New Code
Process Verification  Enter the above shown code:*
Inform me about updated answers to this question

   
Related Questions
View Answer
Is there any way to write a class such that no class can be inherited from it. Please include code

View Answer
The class which acts as interface between the C++ and the Java layer?

View Answer
What is virtual constructors/destructors?


View Answer
What do you mean by pure virtual functions?


View Answer
What is namespace?


View Answer
What is RTTI?


View Answer
What is a template?


View Answer
What do you mean by inline function?


View Answer
What is virtual class and friend class?
View Answer
What is function overloading and operator overloading?


View Answer

Please Note: We keep on updating better answers to this site. Subscribe to our newsletter to get notified when better answer is posted.

Notify me when better answer is posted!
Email:

View ALL C++ Interview Questions

User Options
Sponsored Links


Copyright ©2003-2010 CoolInterview.com, All Rights Reserved.
Privacy Policy | Terms and Conditions
Page URL: http://www.coolinterview.com/interview/10843/default.asp?cachecommand=bypass


Download Yahoo Messenger | Placement Papers| FREE SMS | ASP .Net Tutorial | Web Hosting | Free SMS | Dedicated Servers | Joke of the Day

0.89