Call a Virtual Function Inside Constructors in C++



In C++, calling a virtual function inside a constructor or destructor is dangerous and should generally be avoided. Following are the reasons to avoid calling:

  • When a constructor (or destructor) is running, the object is not fully built (or fully destroyed).
  • At that time, the virtual function table (vtable) points to the version of the class currently being constructed or destructed, not the most derived version.

What Happens When You Call a Virtual Function in a Constructor?

If you call the virtual function inside a constructor:

  • It will call the base class version of the function, not the derived class version.
  • If the base class has no implementation (e.g., it's a pure virtual function), it can give a runtime error (pure virtual call).

When a virtual function is called inside a constructor, it always calls the version from the class that is currently being constructed, not the overridden version in the derived class.

This happens because, at the time the base class constructor runs, the derived class part of the object has not been created yet.

Virtual Function Call in Constructor

In this example, we demonstrate that calling a virtual function inside a constructor always resolves to the base class version, not the derived class version.

#include<iostream>
using namespace std;
class Base {
public:
 Base() { f(); }
 virtual void f() { std::cout << "Base" << std::endl; }
};
class Derived : public Base {
public:
 Derived() : Base() {}
 virtual void f() { std::cout << "Derived" << std::endl; }
};

int main() {
 Derived d;  
 return 0;
}

The above code generates the following output:

Base

Another Example

Following is another example of calling a virtual function inside a constructor ?

#include<iostream>
using namespace std;
class Animal {
   public: Animal() {
      speak(); // Calling virtual function inside constructor
   }
        
   virtual void speak() {
      cout << "Animal sound" << endl;
   }
};
        
class Dog: public Animal {
   public: Dog(): Animal() {
   // Dog constructor
   }
        
   void speak() override {
      cout << "Dog barks" << endl;
   }
};
int main() {
   Dog d;
   return 0;
}

following is the output:

Animal sound
Updated on: 2025-05-27T16:40:58+05:30

784 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements