Note: Inheritance in object oriented programming is a major concept. If you haven’t understood the OOP principles in C++, read the articles, Understanding Basic Object Orientated Programming and Implementing a class with Object Orientated principles first. 

What is Inheritance in object oriented programming?

Inheritance in object oriented programming is a major concept of forming new classes from existing classes. If you were to create two similar classes, it would be much more efficient to share the same members instead recreating of new ones. This is the advantage of inheritance.

Let’s look at some code that applies to the concept of inheritance.

inheritance code 1

inheritance code 2

To explain how inheritance works, have a look at the visual diagram.

inheritance

Firstly we have defined the first class named Shape. The members are width, height, and set_shape_values(). Now when the triangle class and rectangle class are being declared, the way the shape class members are being inherited is by:

class Triangle: public Shape
class Rectangle: public Shape

Once the class declaration is completed, the functions in the three classes are then implemented.

inheritance code 3

After all the member functions are implemented, we can now enter the int main() code. We create two class objects and enter in values to calculate the area of the rectangle and triangle:

// Create the objects
Triangle trig1;
Rectangle rect1;

// Set values
trig1.set_shape_values(5, 5);
rect1.set_shape_values(3, 5);

Once this has been done, we can then display the calculated values:

// Display values
cout << trig1.Triangle_area_cal() << “\n”;
cout << rect1.Rectangle_area_cal() << “\n”;

Table summary of how we can access members via inheritance

table of inheritance

In the Shape class code, there are two protected members, width and height. These protected members can be accessed because the Rectangle and Triangle class inherit the Shape class members. If width and height were private members, they would only be able to be accessed under the same class name.

Share this post