CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

C++ – Calling Virtual functions from class Constructors

Virtual keyword in C++ is used for polymorphic behavior. C++ allows the creation of virtual functions, virtual destructors, and virtual inheritance.

Virtual functions will resolve exact function calls in the inheritance hierarchy, at run-time. This is called 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;
}

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

Let’s slightly change this: Call the “CallDisplay” function from Shape‘s constructor. The code looks 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 the main() function. The Shape is the base class of Circle and its constructor will call before calling Circle‘s constructor. Inside Shape‘s constructor, we are calling the CallDisplay function which calls the virtual function Display.

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

C++ ignores virtual functions from class constructors. Instead of calling a virtual function, it calls the class’s local function. There are good reasons to ignore virtual functions from class constructors. From the 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 the Circle class itself is not created; how can the Shape class call its derived class’s method? That is the reason, C++ ignores virtual functions from its class’s constructors.

**

C++ – Calling Virtual functions from class Constructors

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top