Junior — Middle
Explain the features of calling a virtual function inside a class constructor and what consequences it may have.
sobes.tech AI
Answer from AI
In C++, when calling a virtual function inside a constructor (or destructor), the version of the function corresponding to the current class is called, not the derived class. This is because during the execution of the constructor, the object is considered an instance of the current class, and the virtual call mechanism does not consider derived classes, as they are not yet initialized.
Consequences:
- If a virtual function is overridden in a derived class, calling it inside the base class constructor will not invoke the overridden version, but the base version.
- This can lead to unexpected behavior if the overridden function uses state that has not yet been initialized.
Example:
#include <iostream>
class Base {
public:
Base() {
foo(); // call to virtual function
}
virtual void foo() {
std::cout << "Base::foo" << std::endl;
}
};
class Derived : public Base {
public:
int* data;
Derived() : data(new int(42)) {}
void foo() override {
std::cout << "Derived::foo, data = " << (data ? *data : 0) << std::endl;
}
};
int main() {
Derived d;
return 0;
}
The output will be:
Base::foo
Because during the execution of the Base constructor, the object is not yet a Derived, and the call to foo() will invoke Base::foo. It is important to consider this to avoid errors and unpredictable behavior.