Home > Backend Development > C++ > Why is the Grandmother Class\'s Default Constructor Called in Virtual Inheritance?

Why is the Grandmother Class\'s Default Constructor Called in Virtual Inheritance?

DDD
Release: 2024-11-16 22:22:03
Original
938 people have browsed it

Why is the Grandmother Class's Default Constructor Called in Virtual Inheritance?

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) { ... }
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template