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;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?