Virtual Constructor in C++

Hi guys, today we try to see whether a virtual constructor in C++ possible or not.

Before we start, I would recommend you to study and learn about Virtual Functions.

C++ example of Virtual Constructor

Now, let us discuss whether we can create a virtual constructor or not. So the answer is NO. We can not make a constructor virtual. There are many reasons behind it like:

  • Whenever a constructor is called, there is no virtual table in the memory. Hence, we can not make virtual constructors.
  • Since the object is not created, virtual construction is impossible.
  • Before creating an object, the compiler must know what type of object is to be created.

We can use only inline before the constructor and nothing else.

But yes, we can create a virtual destructor because the destructor is called at the end of the scope. And at that time, the virtual table exists in the memory.

Let us see a snippet in which we will try to create a virtual constructor.

#include <iostream>
using namespace std;
class base
{
    public:
    virtual base()                        // Virtual Constructor
    {
        cout << "base class" << endl;
    }
    void show()
    {
        cout << "base class-show" << endl;
    }
};
class derived: public base
{
    public:
    derived()
    {
        cout << "derived class" << endl;
    }
    void show()
    {
        cout << "derived class-show" << endl;
    }
};
int main()
{
    base* ptr;
    derived d;
    ptr = &d;
    ptr->show();
}

Output:

constructors cannot be declared 'virtual' [-fpermissive]

In this above code, we are trying to make a virtual constructor which is not possible, and hence the expected output is coming.

Now, let me show an example of virtual destructor which is definitely possible in C++

#include <iostream>
using namespace std;
class base
{
    public:
    virtual ~base()                            //Virtual Destructor
    {
        cout << "base class-destruct" << endl;
    }
    void show()
    {
        cout << "base class-show" << endl;
    }
};
class derived: public base
{
    public:
    ~derived()
    {
        cout << "derived class-destruct" << endl;
    }
    void show()
    {
        cout << "derived class-show" << endl;
    }
};
int main()
{
    base* ptr;
    derived d;
    ptr = &d;
    ptr->show();
}

Output:

base class-show
derived class-destruct
base class-destruct

 

So, as you can see the code for virtual destructor is working absolutely fine.

You can visit Virtual Destructor in C++ for more details on Virtual Destructor.

Leave a Reply

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