Default Constructor Invocation in Virtual Inheritance
Virtual inheritance, a C inheritance mechanism, aims to resolve the problem of diamond inheritance or repetitive inheritance. In this context, a question arises: why is the default constructor of the virtual base class invoked when instantiating a derived class object?
This behavior stems from the design of virtual inheritance. Unlike traditional inheritance, where the base class constructor is called by the derived class constructor via the initialization list, in virtual inheritance, the constructor of the most derived class directly calls the constructor of the virtual base class.
In the example provided:
class grandmother { public: grandmother() { std::cout << "grandmother (default)" << std::endl; } grandmother(int attr) { std::cout << "grandmother: " << attr << std::endl; } }; class mother: virtual public grandmother { public: mother(int attr) : grandmother(attr) { std::cout << "mother: " << attr << std::endl; } }; class daughter: virtual public mother { public: daughter(int attr) : mother(attr) { std::cout << "daughter: " << attr << std::endl; } };
When instantiating an object of type daughter, the daughter constructor directly calls the grandmother constructor. However, since no specific constructor is invoked in the initialization list of the daughter constructor, the default constructor of grandmother is called by default.
To explicitly call the desired constructor, the initialization list of the daughter constructor must be modified to:
daughter(int attr) : grandmother(attr), mother(attr) { ... }
By doing so, the correct constructor of grandmother is invoked, and the output will include the following line:
grandmother: 0
Understanding this behavior is crucial when working with virtual inheritance, as it ensures proper initialization and object construction.
The above is the detailed content of Why is the Default Constructor of a Virtual Base Class Invoked when a Derived Class Object is Instantiated?. For more information, please follow other related articles on the PHP Chinese website!