Virtual call from constructor or destructor in C++

Hello everyone, In this tutorial, we will learn about calling the virtual function from the constructor or the destructor of the class in C++. Before moving to this topic you should have prior knowledge of virtual function (learn Virtual Function in C++). But calling the virtual function from the constructor or destructor in c++ might be very dangerous.

You might be calling it from the base class and not the derived class because in inheritance whenever a derived class object is created base class constructor is called first. So mostly virtual function is not called in the constructor or destructor.

Calling virtual function from constructor or destructor

Let’s see how to implement it using the C++ code:

#include <iostream>

using namespace std;

class negative{
    public:
        int n;
        
        negative()
        {
            assign();
        }
        
        virtual void assign()
        {
            n= -1;
        }
        
};
class positive : public negative{
    public:
        positive() 
        {
            negative();
        }
        virtual void assign()
        {
            n=1;
        }
    
        int get()
        {
            return n;
        }
};

int main()
{
    positive obj;
    std::cout<<"The value is n = "<<obj.get();
}

 

Output:

The value is n = -1

Explanation:

  1. The program always starts from main function so first the object of class positive is being created.
  2. After that as soon as the object is created constructor is also called automatically.
  3. Now, here as it is inheritance first the base class constructor is called and then the derived class.
  4. Here in the base class constructor, we have called the virtual function named assign so it will initialize the value of n to -1.
  5. Now constructor of a derived class is called and inside it, we have called the constructor of the base class.
  6. So again the value of n is initialized to -1 just because of virtual function assign of the base class.
  7. Now the get function is called so get function will return the value stored in n, and it will print -1.

As seeing the code we expected our answer to be positive i.e. 1. But because of calling the virtual function in the constructor, our value got changed. So the virtual function is not called in the constructor or destructor.

Also read,

Leave a Reply

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