Sobes.tech
Junior — Middle

What behavior is expected when calling a virtual function inside a class constructor?

sobes.tech AI

Answer from AI

When calling a virtual function inside a constructor (or destructor) of a class in C++, the version of the function defined exactly in the current class is called, not in derived classes.

This is because, during the execution of the constructor, the object is not yet considered an instance of the derived class, so the virtual call mechanism does not switch to overridden versions.

Example:

class Base {
public:
    Base() { foo(); }
    virtual void foo() { std::cout << "Base::foo" << std::endl; }
};

class Derived : public Base {
public:
    Derived() : Base() {}
    void foo() override { std::cout << "Derived::foo" << std::endl; }
};

// When creating a Derived object, Base::foo() will be called in the Base constructor
Derived d; // Will output "Base::foo"

Thus, virtual calls in constructors and destructors do not work polymorphically.