Virtual Destructors in C++

If multiple objects are created dynamically in the derived class, a dangerous situation occurs. More and more un-referenced memory blocks will clutter up the main memory without you being able to reallocate them—this can seriously impact your program’s response and even lead to external memory being swapped in. This issue can be solved simply by declaring virtual destructors.

A class used as a base class for other classes should always have a virtual destructor defined. Even if the base class does not need a destructor itself, it should at least contain a dummy destructor, that is, a destructor with an empty function body.

Just like a member functions as virtual, destructors can be declared as virtual, whereas constructors can not be virtual.

Virtual Destructors are controlled in the same way as virtual functions. When a derived object pointed to by the base class pointer is deleted, destructor of the derived class as well as destructor of all its base classes are invoked. If destructor is made as non virtual destructor in the base class, only the base class’s destructor is invoked when the object is deleted.

Example:

#include<iostream.h>
#include<string.h>
class father
{
	protected:
		char *fname;
	public:
		father(char *name)
		{
			fname=new char(strlen(name)+1);
			strcpy(fname,name);
		}
		virtual ~father()
		{
			delete fname;
			cout<<”~father is invoked…”;
		}
		virtual void show()
		{
			cout<<”father name…”<<fname;
		}
};
class son: public father
{
	protected:
		char *s_name;
	public:
		son(char *fname,char *sname):father(fname)
		{
			sname=new char[strlen(sname)+1];
			strcpy(s_name,sname);
		}
		~son()
		{
			delete s_name;
			cout<<”~son() is invoked”<<endl;
		}
		void show()
		{
			cout<<”father’s name”<<fname;
			cout<<”son’s name:”<<s_name;
		}
};
void main()
{
	father *basep;
	
	basep =new father (“mona”);
	cout<<”basep points to base object…”
	
	basep->show();
	delete basep;
	
	basep=new son(“sona”,”mona”);
	cout<<”base points to derived object…”;
	
	basep->show();
	delete basep;
}

Related posts