Difficulty: Easy
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:
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:
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:
Final Answer:
It is used to avoid multiple copies of base class in derived class.
Discussion & Comments