Skip to main content

Most Visited Blog

How to Install minGW C++ compiler for Windows - Cyborg Coding

Multiple inheritance in C++ with example - Cyborg Coding

Multiple inheritance in C++ is a type of inheritance where a derived class can inherit properties and methods from multiple base classes. This means that a class can have multiple parent classes, and inherit the properties and methods of each of them. This allows for code reuse, as the derived class can use the properties and methods of multiple base classes without having to rewrite the same code.

However, multiple inheritance can also lead to complex and hard-to-understand code, especially when dealing with ambiguities and virtual bases. Ambiguities can occur when a derived class inherits multiple properties or methods with the same name from different base classes. To avoid these issues, C++ uses virtual inheritance, where a class can inherit from a base class multiple times, but only one instance of the base class is created.

An example of multiple inheritance in C++ is:

class Shape {
public:
    double getArea() { /* code */ }
};

class Color {
public:
    std::string getColor() { /* code */ }
};

class Square : public Shape, public Color {
private:
    double side;
public:
    Square(double s) : side(s) {}
    double getArea() { return side*side; }
    std::string getColor() { return "red"; }
};

In this example, the class "Square" inherits from both "Shape" and "Color" classes. The "Shape" class has a method to calculate the area of a shape, and the "Color" class has a method to get the color of an object. The "Square" class inherits both methods and can use them without having to rewrite the same code.

In summary, multiple inheritance in C++ is a type of inheritance where a derived class inherits from multiple base classes. It allows a class to inherit properties and methods from multiple sources, making it a powerful tool for code reuse. However, it can also lead to complex and hard-to-understand code, so C++ uses virtual inheritance to avoid these issues.

Comments