Virtual destructors are controlled in the same way as virtual functions. When a derived obje ct pointed to by the base class pointer is deleted, destructor of the derived class as well as destructors of all its base classes are invoked. If the destructor is made non-virtual destructor in the base class, only the base class’s destructor is invoked when the object is deleted.
Sample Program
#include <iostream.h>
class Father
{
protected:
char *fname;
public:
Father(char *name)
{
name = new char[strlen[name]+1]
strcpy(fname,name);
}
virtual ~Father()
{
delete fname;
cout<<”Father destructor”<<endl;
}
virtual void show(void)
{
cout<<”Father’s name”<<fname<<endl;
}
};
class Son:public Father
{
protected:
char *sname;
public:
Son(char *sn, char *fn):Father(fn)
{
sn = new char[strlen(sn}+1]
strcpy(sname,sn);
}
~Son()
{
delete sname;
cout<<”~son() is invoked”<<endl;
}
void show(void)
{
cout<<”Father name”<<fname<<endl;
cout<<”Son name”<<sn<<endl;
}
};
void main()
{
Father *Bp;
Bp = new Father(“James”);
Cout<<”Base pointes to base object….”<<endl;
Bp->show();
delete Bp;
Bp = new Son(“kdvam”,”dav”);
cout<<”Base pointes to derived object….”<<endl;
Bp->show();
Delete Bp;
}
the base class destructor is declared as virtual and basep actually addresses the son’s object and hence, the destructors in the son’s class as well as the father’s class are invoked. Note that while constructing an object, the constructors are invoked from the top of a hierarchy upto the current class and while hierarchy.
Virtual Destructor is used in the following situations:
? A virtual destructor is used when one class needs to delete object of a derived class that are addressed by the base-pointers and invoke a base class destructor to release resource allocated to it.
? Destructors of a base class should be declared as virtual fucntions. When delete operations in performed on the object by a pointer or reference, the program will first call the object destructor instead of the destructor associated with the pointer or reference type.
No comments:
Post a Comment