Inheritance is a fundamental concept in object-oriented programming that allows you to create new classes (derived classes) based on existing classes (base classes). It promotes code reusability, modularity, and the creation of hierarchical relationships between classes.
Types of Inheritance
Let's delve deeper into the three primary types of inheritance:
1. Single Inheritance
In single inheritance, a derived class inherits from only one base class.
Example:
#include <iostream>
using namespace std;
class Animal {
public:
void eat() {
cout << "Eating..." << endl;
}
};
class Dog : public Animal {
public:
void bark() {
cout << "Woof!" << endl;
}
};
int main() {
Dog dog;
dog.eat();
dog.bark();
return 0;
}
In this example, the Dog class inherits from the Animal class. It can access and use the eat() method inherited from the base class.
2. Multiple Inheritance
In multiple inheritance, a derived class inherits from multiple base classes.
Example:
#include <iostream>
using namespace std;
class Vehicle {
public:
void start() {
cout << "Starting..." << endl;
}
};
class Engine {
public:
void ignite() {
cout << "Igniting..." << endl;
}
};
class Car : public Vehicle, public Engine {
public:
void drive() {
start();
ignite();
cout << "Driving..." << endl;
}
};
int main() {
Car car;
car.drive();
return 0;
}
In this example, the Car class inherits from both the Vehicle and Engine classes, gaining the properties and methods of both.
3. Multilevel Inheritance
In multilevel inheritance, a derived class inherits from a base class, which in turn inherits from another base class.
Example:
#include <iostream>
using namespace std;
class Vehicle {
public:
void start() {
cout << "Starting..." << endl;
}
};
class Car : public Vehicle {
public:
void drive() {
start();
cout << "Driving..." << endl;
}
};
class SportsCar : public Car {
public:
void race() {
drive();
cout << "Racing..." << endl;
}
};
int main() {
SportsCar sportsCar;
sportsCar.race();
return 0;
}
In this example, the SportsCar class inherits from the Car class, which in turn inherits from the Vehicle class.
Remember that while inheritance is a powerful tool, it should be used judiciously to avoid complex class hierarchies and potential ambiguity issues.
Commentaires