Why is Default Constructor Called in Virtual Inheritance?
When creating a new object of a daughter class using virtual inheritance, the default constructor of the grandmother class is unexpectedly invoked. This behavior may seem counterintuitive, considering that the user explicitly calls the mother class constructor with an argument.
Explanation:
In virtual inheritance, the constructor of the virtual base class is invoked directly by the constructor of the most derived class. In the given code, the daughter class is the most derived class and, therefore, it directly calls the grandmother constructor.
Since the daughter class does not provide any arguments to the grandmother constructor in the initialization list, the default constructor of the grandmother class is automatically called. This is because, by default, the compiler assumes that the default constructor should be used when no specific constructor is invoked.
Solution:
To call the desired grandmother constructor with an argument, the initialization list of the daughter class constructor must be explicitly updated. The correct code is:
daughter(int attr) : grandmother(attr), mother(attr) { ... }
This ensures that the grandmother constructor is called with the specified argument. Alternatively, the grandmother class can provide a default constructor that accepts an argument.
The above is the detailed content of Why is the Grandmother Class\'s Default Constructor Called in Virtual Inheritance?. For more information, please follow other related articles on the PHP Chinese website!