Welcome to another exciting lesson on C++ programming! Today, we're going to dive deep into a fascinating concept known as Multilevel Inheritance. This is an extension of single and multiple inheritance, where a derived class inherits from another derived class instead of a base class. Let's get started!
Multilevel inheritance is a process where a class derives properties from another class, which in turn derives properties from another base class. It allows us to create complex hierarchies of classes and reuse code effectively.
Here's a simple illustration:
// Base class
class Animal {
public:
void eat() { cout << "Eating..." << endl; }
};
// Derived class (first level)
class Mammal : public Animal {
public:
void breathe() { cout << "Breathing..." << endl; }
};
// Derived class (second level)
class Cat : public Mammal {
public:
void meow() { cout << "Meow..." << endl; }
};In the example above, we have a base class Animal, a derived class Mammal that inherits from Animal, and another derived class Cat that inherits from Mammal. This forms a multilevel inheritance hierarchy.
To create multilevel inheritance in C++, you simply need to define a class that inherits from another class, which in turn may inherit from another base class or derived class. Here's another example to make it clearer:
// Base class
class Vehicle {
public:
void run() { cout << "Vehicle is running..." << endl; }
};
// Derived class (first level)
class Car : public Vehicle {
public:
void steer() { cout << "Steering a car..." << endl; }
};
// Derived class (second level)
class Sedan : public Car {
public:
void soundHorn() { cout << "Beep beep!" << endl; }
};In this example, we have a base class Vehicle, a derived class Car that inherits from Vehicle, and another derived class Sedan that inherits from Car. Now, a Sedan object can run, steer, and sound its horn.
What is Multilevel Inheritance in C++?
That's all for today's lesson on C++ Multilevel Inheritance! In the next lesson, we'll explore more complex examples and dive deeper into this powerful concept.
Remember, practice makes perfect! Keep coding and learning! š