class baseClass { public :       ~baseClass() { cout<< "baseClass Des
called"<< endl; } };
....
int main()
{
baseClass *bPtr = new derivedClass2();
delete bPtr;
}
This will print :"baseClass Des called"
Reason:
The baseClass is a simple class there is no virtual destructor for
it,so whenever we create the object of classes derived from baseClass
there will be memory leak for the Derived Object.
There is no way for the compiler to interpret differently the
destructor function..so it calls baseClass destructor functions only.
If we make it virtual Destructor then this will be determined at run
time through the v-table based on its object type and derived
destructor will be executed 1st then base destructor.


In the below case:
/*Derived class*/
class derivedClass1 : public baseClass {
public:
    virtual ~derivedClass1() {cout <<"derivedClass1 Des called"<<
endl;}

};
class derivedClassOf1 : public derivedClass1{
public:
    virtual ~derivedClassOf1() {cout <<"derivedClassOf1 Des called"<<
endl;}
};

Now derivedClass1  has virtual destructor so all the derived objects
of this class will not have any memory leak provided if
derivedClass1 *pdC1=new derivedClassOf1 ();
delete pdC1;
This will 1st call derivedClassOf1,then derivedClass1 and also the
base class(remember deletion via derived pointer will make sure the
base destructor will be called,virtual was added to solve the problem
of memory leak while deletion from base pointers)


baseClass *p=new derivedClassOf1 ();
This will have memory leak as it will call only the base class
destructor.

-- 
You received this message because you are subscribed to the Google Groups 
"Algorithm Geeks" group.
To post to this group, send email to algogeeks@googlegroups.com.
To unsubscribe from this group, send email to 
algogeeks+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/algogeeks?hl=en.

Reply via email to