Course Content
C++ OOP
C++ OOP
Mulptiple Inheritance
Multiple inheritance allows a derived class to inherit from multiple base classes. This means that a single derived class can have access to the members (data and functions) of multiple base classes, effectively combining their attributes and behaviors.
Horizontal Multiple Inheritance
In this type of multiple inheritance, a class inherits properties and methods from multiple superclasses at the same level in the inheritance hierarchy. Consider classes
: Shape
and Color
, each with distinct properties and methods. The Shape
defines the shape of an object, and the Color
defines its color.
Shape.h
Color.h
class Shape { public: void setShape(const std::string& value) { shape = value; } std::string getShape() { return shape; } private: std::string shape; };
Now, let's create a subclass called ColoredShape
that inherits properties and methods from both Shape
and Color
classes.
ColoredShape.h
#include "Shape.h" #include "Color.h" class ColoredShape : public Shape, public Color { public: void describe() { std::cout << "This object is a " << getShape() << " shape and is " << getColor() << '\n'; } };
Vertical Inheritance
In depth inheritance, a class
inherits properties and methods from its direct parent and its ancestors, forming an inheritance chain. For instance, consider the class
Vehicle
, which can serve as a basis for inheriting for Car
, Truck
, and others. In our example, we will utilize the Car
to illustrate the concept.
Vehicle.h
Car.h
class Vehicle { public: void start() { std::cout << "Vehicle started"; } void stop() { std::cout << "Vehicle stopped"; } };
Now, to achieve vertical inheritance, you have to set up a hierarchy where one class
inherits from another, and then a subsequent class inherits from the first one, and so on. We can create an ElectricCar
that inherits all properties and functionalities from the Car
, which itself inherits from the Vehicle
, establishing a complex multiple inheritance structure.
ElectricCar.h
#include "Car.h" class ElectricCar : public Car { public: void charge() { std::cout << "Electric car is charging"; } };
Why Multiple Inheritance is Needed
Multiple inheritance provides flexibility and code reuse in situations where a class
needs to exhibit behaviors or characteristics of more than one parent class
. Here are some scenarios where multiple inheritance is beneficial:
Real-world roles: a flying bird can combine features from both
Flying
andBird
classes, representing both abilities. TheFlying
class can also apply to planes or other flying objects.Code reuse: multiple inheritance lets a class reuse features from different base classes without duplication.
Focused interfaces: encourages combining small, specific interfaces instead of using one large, general one.
Split a complex object into simpler ones and utilize multiple inheritance to create flexible and maintainable software.
Thanks for your feedback!