Why Virtual Functions Can't Be Called from Constructors
In C , virtual functions play a crucial role in polymorphism by enabling objects of derived classes to override methods inherited from their base classes. However, a common misconception arises when attempting to call virtual functions from within class constructors.
Consider the following example code:
struct base { virtual const int value() const { return 0; } base() { std::cout << value() << std::endl; } virtual ~base() {} }; struct derived : public base { virtual const int value() const { return 1; } }; int main(void) { derived example; }
When this code executes, it outputs "0" instead of the expected "1". Why?
The reason lies in the order of constructor execution. When a derived class object is created, the base class constructor is invoked first. At this point, the derived class object is not yet fully constructed, and its virtual methods cannot be reliably called.
When the base class constructor calls value(), it accesses the base class implementation of the virtual function because the derived class has not "matured" into a derived object yet. To ensure that virtual functions are called correctly, they must be accessed from within fully constructed objects.
Therefore, to fix the code and output "1", the value() method call in the base class constructor must be removed or postponed until after the object has been fully constructed.
The above is the detailed content of Why Do Virtual Functions Called in a Constructor Return the Base Class Implementation?. For more information, please follow other related articles on the PHP Chinese website!