Virtual Constructor in C++



In C++, we cannot create a virtual constructor, this is because C++ is a statically typed language and the constructor is responsible for creating an object. So, the compiler needs to know the exact type of object at compile time.

The virtual mechanism works only when we have a base class pointer to a derived class object.

The constructor cannot be virtual, because when a constructor of a class is executed there is no virtual table in the memory, means no virtual pointer defined yet. So, the constructor should always be non-virtual.

Implementation of Constructor & Destructor

In the following example, we implement a virtual destructor in inheritance:

Open Compiler
#include<iostream> using namespace std; class b { public: b() { cout << "Constructing base \n"; } virtual~b() { cout << "Destructing base \n"; } }; class d: public b { public: d() { cout << "Constructing derived \n"; } ~d() { cout << "Destructing derived \n"; } }; int main(void) { d * derived = new d(); b * bptr = derived; delete bptr; return 0; }

Following is the output of the above code

Constructing base 
Constructing derived 
Destructing derived 
Destructing base 
If we try to make a constructor virtual compiler will flag an error. Apart from the inline keyword, no other key can be used in the constructor declaration.

Implementation of Virtual Constructor

In the following example, we attempt to create a virtual constructor:

Open Compiler
#include<iostream> using namespace std; class b { public: // attempt to create virtual constructor virtual b() { cout << "Constructing base \n"; } }; class d: public b { public: d() { cout << "Constructing derived \n"; } }; int main(void) { d * derived = new d(); b * bptr = derived; return 0; }

Following is an error, if you try to attempt virtual constructor:

constructors cannot be declared 'virtual' [-fpermissive]
    6 |    virtual b() {
Updated on: 2025-05-27T16:31:50+05:30

384 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements