Constructor Invocation of Virtual Functions
In C , constructors are responsible for initializing objects. However, when dealing with derived classes and virtual functions, specific behavior can arise that may not be immediately intuitive.
Consider the following example:
#include <iostream> 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; }
In this example, we have a base class base with a virtual function value(). A derived class derived inherits from base and overrides value(). The constructor in base attempts to call value() within its constructor.
When the constructor of derived is invoked, the constructor of base is called first. At this point, the object is still in the state of the base class, and value() resolves to the base class's implementation. This is why the program prints "0" instead of the expected "1".
To address this issue, we need to ensure that the object is fully initialized as the derived class before calling value() in the constructor. One way to achieve this is to delay the call to value() until after the constructor of derived has been executed, which can be done by using a virtual function in the derived class constructor.
The above is the detailed content of Why Does Calling a Virtual Function in a Base Class Constructor Print the Base Class Value, Not the Derived Class Value?. For more information, please follow other related articles on the PHP Chinese website!