How do I resolve diamond inheritance with virtual inheritance?

Diamond inheritance occurs when a class inherits from two classes that both inherit from a common base class. This can lead to ambiguity and redundancy in the inheritance hierarchy. Virtual inheritance is used in C++ to resolve these issues by ensuring that only one instance of the base class is shared across the derived classes.

Using virtual inheritance, we can prevent multiple base class instances in the diamond shape of inheritance. This example illustrates how to use virtual inheritance to resolve diamond inheritance.

// Example of virtual inheritance to resolve diamond inheritance #include class Base { public: Base() { std::cout << "Base Constructor" << std::endl; } void display() { std::cout << "Base class display" << std::endl; } }; class DerivedA : virtual public Base { public: DerivedA() { std::cout << "DerivedA Constructor" << std::endl; } }; class DerivedB : virtual public Base { public: DerivedB() { std::cout << "DerivedB Constructor" << std::endl; } }; class Final : public DerivedA, public DerivedB { public: Final() { std::cout << "Final Constructor" << std::endl; } }; int main() { Final obj; obj.display(); // Calls the display function from Base class return 0; }

C++ diamond inheritance virtual inheritance base class derived classes multiple inheritance