Inheritance allows a class to derive features (attributes and methods) from another class. This creates a "Parent-Child" relationship.
1. Key Terminology
Base Class (Parent): The class whose features are inherited.
Derived Class (Child): The class that inherits from the Base class.
Reusability: Instead of rewriting code for similar objects, the Child class automatically gets everything the Parent has.
2. The "Is-A" Relationship
Use inheritance when an object is a specialized version of another.
A
Caris aVehicle.A
Manageris anEmployee.
Code Example: Vehicle System
In this example, the Car class inherits from Vehicle. It gains the brand and honk() method without us having to type them again.
#include <iostream>
#include <string>
using namespace std;
// Base Class (Parent)
class Vehicle {
public:
string brand = "Ford";
void honk() {
cout << "Beep! Beep!" << endl;
}
};
// Derived Class (Child)
// Syntax: class Child : public Parent
class Car : public Vehicle {
public:
string modelName = "Mustang";
};
int main() {
Car myCar;
// Accessing Parent members through the Child object
myCar.honk();
cout << "Brand: " << myCar.brand << endl;
cout << "Model: " << myCar.modelName << endl;
return 0;
}3. Access Levels in Inheritance
publicmembers: Staypublicin the child.privatemembers: Are not accessible by the child class.protectedmembers: A special middle ground—hidden from the outside world, but accessible to child classes.