Open In App

Calling virtual methods in constructor/destructor in C++

Prerequisite: Virtual Function in C++
Calling virtual functions from a constructor or destructor is considered dangerous most of the times and must be avoided whenever possible. All the C++ implementations need to call the version of the function defined at the level of the hierarchy in the current constructor and not further. 
You can call a virtual function in a constructor. The Objects are constructed from the base up, “base before derived”.
 




// CPP program to illustrate
// calling virtual methods in
// constructor/destructor
#include<iostream>
using namespace std;
 
class dog
{
public:
    dog()
    {
        cout<< "Constructor called" <<endl;
        bark() ;
    }
 
    ~dog()
    {
        bark();
    }
 
    virtual void bark()
    {
        cout<< "Virtual method called" <<endl;
    }
 
    void seeCat()
    {
        bark();
    }
};
 
class Yellowdog : public dog
{
public:
        Yellowdog()
        {
            cout<< "Derived class Constructor called" <<endl;
        }
        void bark()
        {
            cout<< "Derived class Virtual method called" <<endl;
        }
};
 
int main()
{
    Yellowdog d;
    d.seeCat();
}

Output: 
 



Constructor called
Virtual method called
Derived class Constructor called
Derived class Virtual method called
Virtual method called

Explanation: 
 

NOTE: It is highly recommended to avoid calling virtual methods from constructor/destructor. 
Quiz on Virtual Functions



 


Article Tags :
C++