C++: Calling Virtual functions from class Constructors

Virtual keyword in C++ is used for polymorphic behavior. C++ allows to create virtual functions, virtual destructors and virtual inheritance.

Virtual functions will resolve exact function call in inheritance hierarchy at run-time. This is called a late-binding. That means, what function to call will come to know at run-time instead of compile time.

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

using namespace std;

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

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

// 
int main()
{
	Circle circle;
	circle.CallDisplay();

	return 0;
}

Above code displays “Circle” on screen. Observe that, CallDisplay is base class’s function and it is calling Display function. Display function is a virtual function and CallDisplay is not. When we calling “CallDisplay” function through an instance of Circle; it is calling Display function of Circle; not the Shape‘s Display function. This is because of virtual keyword. This is as we expected.

Lets slightly change this: Call “CallDisplay” function from Shape‘s constructor. The code will like this:

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

using namespace std;

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

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

// 
int main()
{
	Circle circle;

	return 0;
}

Observe that, we have created an instance for Circle in main() function. Shape is the base class of Circle and its constructor will call before calling Circle‘s constructor. Inside Shape‘s constructor we are calling CallDisplay function which calls virtual function Display.

When we run above code; we expect the result “Circle”; but it displays “Shape” message.

C++, ignores virtual functions from class constructors. Instead of calling virtual function, it calls class’s local function. There are good reasons to ignore virtual functions from class’s constructors. From above example: We are calling Display virtual function indirectly from Circle‘s object. It should call Circle‘s Display function as per the virtual function behavior. But Circle class itself is not created; how can Shape class calls its derived class’s method? That is the reason, C++ ignores virtual functions from its class’s constructors.

**

Leave a Reply