Tuesday, July 14, 2009

Delete pointer in c++?

class A{





};





class B: public A


{





protected :


A *a;


public:


~B()


{


if(a !=NULL)


delete a;%26lt;------------ core dump here


}


void fun();





};


void B::fun()


{





a= new c[5];





}





class c:public B


{








};








How to delete pointer a?


destructor of all classes are virtual.

Delete pointer in c++?
You should first initialise pointers to null in constructor. If you don't do this pointer will not be NULL ( if(a!=NULL) ) it will be undefined. you will be trying to delete an undefined memory address.
Reply:first have a forward declaration of class c right at the top coz ven u r trying to allocate memory in b till data stage c is not known to compiler





second u can have a try block in fun() which allocates dyn mem


and a catch block which takes as a paramater of bad_alloc coz new ven fails throws a bad_alloc exception error





Other option is u need to overload the new operator so dat u tel lthe compiler that it can take an argument of class c type


No comments:

Post a Comment