Introduction to Inheritance

Introduction to Inheritance

Inheritance is an important feature of object oriented programming used for code reusability. Inheritance allows us to inherit all the code (except declared as private) of one class to another class. The class to be inherited is called base class or parent class and the class which inherits the other class is called derived class or child class.

Once a class derives another class then the derived class can access all the data members and member function of its parent class(es) other than declared as private.

parent class

In the above figure, suppose A and X are classes where class X inherits class A. In this relationship, A is called parent or base class while X is called child or derived class (we may have more than one parents or child classes as to be discussed in the next article).

Once this relationship is established then class X (child) can access all the code written in class A (parent) in the form of data members and member functions. Only the data members or member functions declared as private are not allowed to be accessed by the child class as private members can only be used in the class where declared.

The main advantage of using inheritance is that in this case we don’t need to write the code written in the parent class.  Once the inheritance is established then the code of parent is automatically available in the child classes. The following code demonstrates that how inheritance is done and how the code of parent class is used by the object of the child class.

child class

child class2

In the above code a class Person is defined in lines 5 to 23. This class is inherited by class Student at line 24 using the following statement.

class Student: public Person

In this statement, a colon (:) shows that class Person is being inherited by class Student. In this inheritance Student becomes derived (child) class and class Person becomes parent (base) class.

 The access specifier public with Person class defines the scope of the members of parent class. If we skip to mention the public keyword here, then the default access specifier is applied here which is private in C++.

It means that the members of Person class are treated as private and will not be accessed in the derived class. If the access specifier is mentioned as public then the derived class will be able to use the members of the parent class as shown at lines 40, 41 and 43.

We can see that the object of child class is using the data members of parent class just like they are defined in Student class. This is due to inheritance. As mentioned before, once inheritance is made then all the members of parent class are available to be used in child class or by the object of child class unless they are not declared as private.

More Related Articles For You

    C++ Tutorial

    C++ Quizzes


Shortcodes Ultimate

Follow Us