C++ inheritance is a simple approach to simulate a Is A relationship in C++. This key notion in object-oriented programming (OOP) allows the construction of new classes from existing ones, enabling code reuse and hierarchical relationships between types.
Modeling the Is A Relationship in C++
The “Is A” connection describes a situation in which one type is a more specialized variety of another. A PassCar “is a” certain kind of automobile, for instance, or an mp3_file “is an” OS_file. This implies that an object of the specialised (derived) class may be thought of as an object of the generic (base) class.
To make this relationship in C++, a new class (called the derived class, child class, or subclass) is derived from an existing class (called the base class, parent class, or superclass).” A class derived by public inheritance inherits the base class’s traits and features and has a public interface.
Reusing code is a major feature of this strategy. Since the derived class inherits member methods and data members from its base class, development is faster and more reliable. Following classes commonly inherit from a base class in a hierarchical class structure. Although base classes define their common members, derived classes define their specialised members.
“Is A” vs. “Has A” Relationships
The “Has A” and “Is A” relationships must be distinguished from one another.
- “Is A” implies inheritance in situations where the derived class is a type of the base class, for as when a manager can be a worker.
- In composition, sometimes referred to as containership or aggregation, “Has A” implies that an object of one class holds a member of another class. For example, a string object in an Account object represents the account holder’s name.
Code Example
#include <iostream>
// Base Class (General)
class Vehicle {
public:
void accelerate() {
std::cout << "Vehicle is accelerating." << std::endl;
}
void brake() {
std::cout << "Vehicle is braking." << std::endl;
}
};
// Derived Class (Specific) - "Car IS A Vehicle"
class Car : public Vehicle {
public:
void drive() {
std::cout << "Car is being driven." << std::endl;
}
};
int main() {
Car myCar; // Create a Car object
// A Car IS A Vehicle, so it can do what a Vehicle can do:
myCar.accelerate(); // Inherited from Vehicle
myCar.brake(); // Inherited from Vehicle
// And a Car can do what only a Car can do:
myCar.drive(); // Specific to Car
return 0;
}
Output
Vehicle is accelerating.
Vehicle is braking.
Car is being driven.
You can also read What is Overloadable And Non-Overloadable Operators In C++?