What is Inheritance?
Explore the concept of inheritance in C++ to understand how derived classes inherit data members and functions from base classes. This lesson helps you grasp IS-A relationships, enabling efficient code reuse and better organization through practical examples of Vehicle, Car, and Ship classes.
Why do We Need Inheritance?
In the classes chapter, we’ve covered the HAS-A relationship. We know a class HAS-A data members and member functions. Now, we want the data members, and member functions of the class are accessible from other classes. So, the capability of a class to derive properties and characteristics from another class is called Inheritance. In inheritance, we have IS-A relationship between classes e.g a car is a vehicle and a ship is a vehicle.
Let’s take the example of Vehicle here.
Vehicle Class
In a Vehicle class, we have many data members like Make, Color, Year and Model. A Vehicle HAS-A Model, Year, Color and Make.
Implementation of Vehicle Class
Let’s look at the implementation of Vehicle class:
The following illustration depicts the structure of the Vehicle class:
These attributes are also attributes of all Cars, Ships and Airplanes but every type of vehicle has some attributes that are different from other types of vehicles, as we will see in detail.
Car Class
The implementation of a Car class needs the same data members and member functions of Vehicle class but we have to include them in the Car class. Cars do have a trunk and every trunk has a capacity to store things upto some limit.
Implementation of Car Class
Let’s look at the implementation of the Car class:
The following illustration depicts the structure of the Car class:
Ship Class
The implementation of a Ship class needs the same data members and member functions of Vehicle class but we have to include them in the Ship class. Ships do have anchors and they vary in numbers.
Implementation of Ship Class
Let’s look at the implementation of the Ship class:
The following illustration depicts the structure of the Ships class:
In the declared classes for different types of vehicles (Car and Ship), we have many repetitive attributes which should be in one base class and should be inherited in the derived classes.