C++: Calling Virtual functions from class Destructors

C++ allows virtual functions to resolve function calls at run-time. This is called late-binding. Like virtual functions, C++ allows virtual destructors to delete the objects properly in inheritance hierarchy.

C++ allows to call virtual functions from class destructors. But what will happen when it calls virtual function from class destructors? Lets take an example:

// Sample.cpp
// 
#include <iostream>

using namespace std;

class Shape
{
public:
	virtual void Display()
	{
		cout << "Shape" << endl;
	}
};

class Circle : public Shape
{
public:
	void Display()
	{
		cout << "Circle" << endl;
 	}
};

// main() function
// 
int main()
{ 
	Shape *pShape = new Circle();
 	if ( pShape != NULL )
 	{ 
		pShape->Display();

		delete pShape;
	}

	return 0;
}

Compile and run this sample program. Observe the result that; it is displaying “Circle” message.

cl /EHsc Sample.cpp

I the code, we are calling Display function through Shape‘s object. We expect that it will call Shape‘s Display function. Actually it will call Circle‘s Display function. Because “pShape” variable actually holds address of Circle‘s object. So, it will call Circle‘s Display function. This is the correct behavior.

We will call the virtual function from class’s destructor and observe the result. Lets modify our program like below:

// Sample.cpp
// 
#include <iostream>

using namespace std;

class Shape
{
public:
	virtual ~Shape()
	{
		Display();
	}
	virtual void Display()
	{
		cout << "Shape" << endl;
	}
};

class Circle : public Shape
{
public:
	void Display()
	{
		cout << "Circle" << endl;
	}
};

// main() function
// 
int main()
{
	Shape *pShape = new Circle();
	delete pShape;

	return 0;
}

From above program, we expect that; it will display “Circle” message on console; based on our discussion on our previous example code. In this program, we have slightly changed our code such a way that instead of calling Display function from main(), we are calling it from class’s destructor. So, as per virtual function concept, C++ should resolve exact function calling at run-time.

But in this scenario, C++ calls local Display function instead of resolving proper Display function at run-time. C++ ignores virtual functions if we call them from class’s destructors.

The reason is, in inheritance hierarchy, the derived class’s destructor will call first, before calling its base class’s destructor. From our example code, Circle‘s class object will be destroyed, before destroying Shape‘s class object. If we call virtual function from base class’s destructor; how C++ calls derived class’s virtual function; if derived class object already destroyed?. That is the reason, C++ ignores virtual functions from class destructors.

Becuase of this, from the above code, it will display “Shape” message.

..

Leave a Reply