C++ virtual base classes: what is their primary purpose in a multiple-inheritance hierarchy?
-
AIt is used to provide multiple inheritance.
-
BIt is used to avoid multiple copies of base class in derived class.
-
CIt is used to allow multiple copies of base class in a derived class.
-
DIt allows private members of the base class to be inherited in the derived class.
Answer
Correct Answer: It is used to avoid multiple copies of base class in derived class.
Explanation
Introduction / Context:Multiple inheritance can produce the “diamond problem,” where a derived class inherits from two intermediate bases that themselves inherit from the same grand base. Without special handling, the final most-derived class can contain two independent subobjects of the grand base, leading to ambiguity and duplication. Virtual base classes solve this problem.
Given Data / Assumptions:
- Class D derives from B and C; both B and C derive from A.
- We want a single shared A subobject inside D.
- We use the virtual keyword in the base-specifier list.
Concept / Approach:
Declaring inheritance as class B : virtual public A and class C : virtual public A tells the compiler that any most-derived class should contain one shared A subobject, not one per path. The most-derived class is responsible for constructing the virtual base, eliminating ambiguities (e.g., which A::f() or which A data to use) and reducing memory overhead of duplicated subobjects. This feature does not “provide multiple inheritance” by itself; it modifies how a base is shared when multiple inheritance exists. It does not change access control (private members remain inaccessible directly) and certainly is not meant to create multiple copies—quite the opposite.
Step-by-Step Solution:
Identify diamond pattern → risk of duplicate A subobjects. Apply virtual inheritance on the shared base A in intermediate classes. Most-derived class now holds one A; ambiguity eliminated.Verification / Alternative check:
Compile with and without virtual inheritance and inspect object layout or method calls; you will see duplicate A instances without virtual inheritance and one shared A with virtual inheritance, confirming the purpose.
Why Other Options Are Wrong:
Provide multiple inheritance — that is the role of listing multiple bases; virtual affects sharing, not availability.
Allow multiple copies — opposite of the actual goal.
Allow private members to be inherited — access control is unchanged; private remains inaccessible to derived classes.
Common Pitfalls:
- Forgetting that the most-derived class must construct the virtual base explicitly in its member-initializer list.
- Misunderstanding that virtual inheritance affects layout and constructor order.
Final Answer:
It is used to avoid multiple copies of base class in derived class.