C++ - Inheritance
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows one class to inherit the properties (data members and member functions) of another class. It enables code reuse and facilitates the creation of class hierarchies. C++ supports different types of inheritance, including multilevel inheritance and multiple inheritance.
Multilevel Inheritance:
Multilevel inheritance involves deriving a class from another derived class. In this type of inheritance, the derived class serves as the base class for another class. This creates a hierarchical relationship where each derived class inherits the properties of its immediate base class, and so on. Here's an example:
class Animal {
public:
void eat() {
cout << "Animal eats" << endl;
}
};
class Mammal : public Animal {
public:
void walk() {
cout << "Mammal walks" << endl;
}
};
class Dog : public Mammal {
public:
void bark() {
cout << "Dog barks" << endl;
}
};
In this example, Animal is the base class, Mammal is derived from Animal, and Dog is derived from Mammal. Each derived class inherits the properties of its immediate base class, allowing Dog to access the eat() and walk() functions defined in Animal and Mammal classes, respectively.
Multiple Inheritance:
Multiple inheritance allows a class to inherit properties from multiple base classes. It enables a class to combine features from multiple sources. In C++, a class can inherit from multiple classes by specifying multiple base classes separated by commas. Here's an example:
class Shape {
public:
void draw() {
cout << "Drawing shape" << endl;
}
};
class Color {
public:
void setColor() {
cout << "Setting color" << endl;
}
};
class Square : public Shape, public Color {
public:
void display() {
cout << "Displaying square" << endl;
}
};
In this example, Square inherits from both Shape and Color classes. As a result, Square has access to the draw() function from Shape and the setColor() function from Color. This allows Square objects to draw themselves and set their color simultaneously.