Inheritance means using the Pre-defined Code. Inheritance is one of the key concepts in the Object-Oriented Programming language like C++, enabling you to organize classes in a hierarchical form. Just like a child inherits the characteristics of his parents and add specific new attributes of his own. With the help of Inheritance, we use the previously defined code but always Remembers, We are only using that code but not changing that code.
Similarly, in C++, a new class can inherit the existing class’s data members and member functions and add members of its own. This process of creating a new class from an existing class is known as Inheritance. The existing class that is inherited is called the base class, and the new class that inherits the functionality is called the derived class. In some other programming languages, a base class can also refer to a parent, superclass or an ancestor and the derived class referred as a child, subclass or a descendent.
The main advantage of Inheritance is the reusability of the code. Inheritance allows well-tested code to be reused and enables changes to make once and affect all relevant places. Once the base class has been written, tested and appropriately debugged, its functionality can reuse by the derived classes rather than being rewritten from scratch. The derived class inherits the members of the base class and can add members of its own. Thus it reduces the amount of new code that must design, written and tested each time a program developed. It also saves time and increases the reliability of the program. The benefit of reusability is more visible in developing complex projects involving many programmers. Without Inheritance, programmers may spend most of their time rewriting code they have written many times before. But using the concept of Inheritance, the same code can be written only once in the base class and can be reused by different programmers. In general, Inheritance provides the ability to extend an existing class to meet new requirements without affecting the original class in any way.
To illustrate the concept of Inheritance, let us consider the following diagram:
In the above diagram, Class X contains member A and B. Later on, if a Class Y is to add to the program. Which has identical members A and B to that of Class X along with an additional member C. Then instead of writing the code for members A and B again in Class Y. It is better to inherit these members from an already existing Class X and only add additional member C in it as shown. Thus by inheriting the base class’s standard features into the derived class, the code’s size is reduced. It also ensures consistency as standard features do not exist in several classes and therefore, only need to be modified or tested. The Class X from which the features inherited is called the base class and the Class Y that inherits the features is called the derived class.
In the Figure above, the arrow pointing upward from Class Y to Class X indicates that the Class Y derived from the base class X.
It is essential to understand that Inheritance only works in one direction. The derived class inherits the base class members, but the base class does not know anything about derive class. Some authors point arrow from top to bottom indicating that the derived class inherits the base class features.
We’ll be covering the following topics in this tutorial:
Type of Inheritance
In C++, there are various forms of Inheritance. Each form of Inheritance differs from others depending upon whether the class is derived from a single base class or multiple base classes or an existing derived class. Each form of Inheritance enable the class to access members of another class(s) using slightly different techniques different forms of Inheritance are Single Inheritance, Multilevel Inheritance, Hierarchical Inheritance, Multiple Inheritance and Hybrid Inheritance
The choice of the right form of Inheritance depends on the programming objectives that you want to achieve.
1) Single Inheritance there is only one Super Class and Only one Sub Class Means they have one to one Communication between them
2) Multilevel Inheritance a Derived class can also inherited by another class Means in this When a Derived Class again will be inherited by another Class then it creates a Multiple Levels.
It is implemented by defining atleast three classes. Each derived class must have a kind of relationship with its immediate base class.
Fig illustrates Multilevel Inheritance. Here class Second is derived from base class First, which acts as a base class for the derived class Third. The class Third inherits the members of class Second directly as it is explicitly derived from it. In contrast, class First’s members are inherited indirectly into class Third (via class Second). So the class Second acts as a direct base class and class. First act as an indirect base class for class Third. Each parent-child relationship is representing a level. So class First-class Second relationship represents the first level of Inheritance and class Second-class Third represents the second level of Inheritance. As the above class hierarchy contains two levels of Inheritance which thus represents Multilevel Inheritance. In multilevel Inheritance, there is no limit to the number of levels in a class hierarchy.
#include<iostream.h> #include<conio.h> class person { private: char name[20]; long int phno; public: void read() { cout<<"Enter name and phno = "; cin>>name>>phno; } void show() { cout<<"\nName = "<<name; cout<<"\nPhone number = "<<phno; } }; class student : public person { private: int rollno; char course[20]; public: void read() { person::read();//Access person's read() cout<<"Enter rollno and course="; cin>>rollno>>course; } void show() { person::show(); //Access person's show() cout<<"\nRollno = "<<rollno; cout<<"\nCourse = \'<<course; } }; class exam : public student { private: int m[4]; double per; public: void read() ; void cal(); void show() ; }; void exam::read() { student::read();//Access student's read() cout<<"Enter marks :"; for(int i=0;i<4;i++) cin>>m[i]; } void exam::cal() { int tot_marks=0; for(int i=0;i<4;i++) tot marks+=m[i]; per=double(tot_marks)/4; } void exam::show() { student::show();//Access student's show() cout<<"\nMarks :"; for(int i=0;i<4;i++) cout<<m[i]<<"\t"; cout<<"\nPercentage = "<<per; } int main() { clrscr(); exam e1; e1.read(); //Input student's information e1.cal(); //Calculating result of student e1.show(); //Displaying student's information getch(); return 0; }
Explanation: The above program implements multilevel inheritance. The program inputs the students basic and academic information calculates the result and displays all the students’ information. The program consists of three classes, namely person, student and exam. The class person is the base class. The class student is derived from person base class, which acts as a base class for the derived class exam. The exam class inherits the features of student class directly and features of person class indirectly. In main(),the statement
e1.read();
e1.show();
Invokes the respective member functions of exam class as e1 is the object of this class. Look carefully at the definition of read() and show() of the exam class, and you will find that both the member functions access same-named member function of the student class directly and person class indirectly. The statement,
e1.cal();
Invokes the member function cal() of exam class for calculating the result of a student.
Multiple Inheritances
So far, we have been deriving a class from a single base class. However, it is also possible to derive a class from two or more unreleased base classes. When we derive a class from two or more base classes, this form of inheritance is known as Multiple Inheritance. It allows the new class to inherit the functionality of two or more well developed and tested base classes, thus reusing predefined classes’ features. Like Single Inheritance, each derived class in multiple inheritances must have a kind of relationship with its base classes. This form of inheritance is useful in those situations in which derived class represents a combination of features from two or more base classes. For Example: In an educational institute, a member can act like a teacher and a student. He may be a student of higher class as well as teaching lower classes.
The syntax for declaring a derived class which inherited from more than one base classes is
class der_class_name : access_specifier base1, access_specifier base2, ... { //Implementation };
Here access_specifier may be either public, private or protected. Each base class from which class is derived must be specified to the colon’s right after the access specifier and must be separated by commas.
The Fig. shows multiple inheritances in which class Third is derived from class First and class Second, which are independent of each other.
Here, class Third inherits all the members of its base classes First and Second. The following program segment shows how a class Third is derived from two base classes First and Second publicly.
class Third: public First, public Second { //Implementation };
The inheritance rules and the usages of access specifier for each base class member remain the same as in single inheritance. The access to each base class member is independent of the access to the members of other base classes using which you derive your class.
#include<iostream.h> #include<conio.h> class base1 { protected: int x; public: void readx() { cout<<"Enter value of x : "; cin>>x; } void showx() { cout<<"x= "<<x; } }; class base2 { protected: int y; public: void ready() { cout<<"Enter value of y: "; cin>>y; } void showy() { cout<<"\ny "<<y; } }; class der public base1,public base2 { private: int z; public: void add() { z=x+y; //Accessing protected members of base classes } void showz () { cout<<"\nz = "<<z; } }; int main() { clrscr(); der d1; d1.readx();//calling readx() of basel d1.ready();//calling ready() of base2 d1.add();//calling add() of der d1.showx();//calling showx() of basel d1.showy();//calling showy() of base2 d1.showz();//calling showz() of der getch(); return 0; }</span> <span style="color: rgb(0, 0, 0);" data-mce-style="color: #000000;">Output: Enter value of x 10 Enter value of y 20 x = 10 y = 20 z = 30
Explanation: In this program, we define a class base1 containing a protected data member x and public member functions readx() and showx() for inputting and displaying the value of x. Similarly, another class base2 is defined that contains a data member y and two public member function ready() and showy(). The class der is inherited from both the base classes base1 and base2 publicly through multiple inheritances. As the class der is derived publicly from both the base class base1 and base2, the derived class object can access public base el and base2 in the main(). In the main() , the statement d1.readx() ; invokes the member function readx() of the base1 class for inputting value of x. Similarly the statement, d1.ready() ; invokes the ready() of base2 for inputting value of y. The statement d1.add(); invokes the member function add() of the der class to perform addition of values of protected data members x and y as they can be accessed directly in the der class. The remaining statement displays the values of x, y and z.
Hierarchical Inheritance
Inheritance represents the hierarchical arrangement of classes in which a single base class can derive multiple classes. This form of Inheritance in which more than one classes derive from a single base class is hierarchical Inherited. These derived classes can further act as a base class for lower-level multiple derived classes, and this process continues and hence represents the hierarchy of classes.
Each derived class inherits the common members from its base class and can have its members. Hierarchical Inheritance helps to reduce a complex class into simpler classes, like single Inheritance. Each derived class in hierarchical Inheritance must have a kind of relationship with its immediate base class.
The following program implements hierarchical Inheritance. Here, we define a base class person. Then we derive two classes teacher and student. The derived classes inherit the common member’s name, phno, read(), show() from the base class person, and have its members. The public read() and show() of the base class redefined in each derived class to input and display teacher and student information.
#include<iostream.h> #include<conio.h> class person { private: char name[20]; long int phno; public: void read() { cout<<"Enter name and phno = "; cin>>name>>phno; } void show() { cout<<"\nName = "<<name; cout<<"\nPhone number = "<<phno; } }; //Base class specification ends class student : public person { private: int rollno; char course[20]; public: void read() { person::read(); cout<<"Enter rollno and course cin>>rollno>>course; } void show() { person::show(); cout<<"\nRollno = "<<rollno; cout<<"\nCourse = "<<course;</span> <span style="color: rgb(0, 0, 0);" data-mce-style="color: #000000;"> } }; //Derived class specification ends class teacher : public person { private: char dept_name[10]; char qual[10]; public: void read() { person::read(); cout<<"Enter dept_name and qualification = "; cin>>dept_name>>qual;</span> <span style="color: rgb(0, 0, 0);" data-mce-style="color: #000000;"> } void show() { person::show(); cout<<"\nDepartment name = "<<dept_name; cout<<"\nQualification = "<<qual; } }; //Derived class specification ends int main() { clrscr(); student s1; cout<<"Enter student Information\n"; s1.read(); cout<<"Displaying Student Information "; s1.show(); teacher t1; cout<<''\nEnter teacher Information\n"; t1.read(); cout<<"Displaying teacher Information "; t1.show(); getch(); return 0; }
Explanation: In main (), we first creates an object s1 of class student through which we call the read() and show() member functions of student’s class for inputting and displaying student information . Then similarly, we create an object t1 of teacher class for inputting and displaying teacher information.
5) Hybrid Inheritance: – This is a Mixture of two or More Inheritance and in this Inheritance a Code May Contains two or Three types of inheritance in Single Code.
Advantages of Inheritance
Inheritance provides some important benefits if used properly. The following are the advantages of inheritance.
1. Software Reusability: Once the base class has been written, tested and debugged properly, its functionality can be reused by the derived classes rather than being rewritten from scratch. Inheriting from a class doesn’t effect that class’s integrity as the base class’s objects may still be instantiated. The main advantage of reusing the existing class is that it increases the reliability and decreases your program’s maintenance cost because of.’
sharing of code by all the derived classes.
2. Levels of Sharing: Sharing of code can occur at a higher level and lower levels. At higher levels, the same class can be used by multiple users or projects. However, at lower levels, a project involving two or more classes can share a class’s code.
3. Consistent behaviour: When two or more classes inherit a base class, then it is guaranteed that the behaviour they inherit will be the same in all the cases.
4. Software Components: Using inheritance, programmers can develop reusable software components. Software reusable components save a lot of time during program development. It also encourages the reuse of debugged and properly tested high-quality software, increasing the likelihood that a system will be implemented effectively. This powerful capability is attractive to many software vendors that can develop classes for sale and make these classes available to users in object code form. Users can then derive new classes from their library classes easily.
5. Abstraction: A programmer who reuses an already existing software component is only concerned about the component’s purpose and interfaces. However, he is not concerned about the detailed information regarding the techniques used to implement the component. In other words, the programmer is only concerned about what base class provides and not how.
6. Reduces development time: The availability of substantial and useful class libraries delivers the maximum benefit of software reuse through inheritance, reducing development time as programmer concentrates on understanding the portion of a new system.
7. Setting of a Protocol: A class can declare a method that its derived class(s) are expected to implement. This method establishes a protocol that all its derived classes must implement that same-named method. When different classes implement the same-named method, a program can better use polymorphism in its design.
8. Easy to bring changes: Library code reused in our programs keeps on constantly improving by the libraries’ developers. So, the benefits of these improvements can be made in your programs by upgrading the library version without changing the interface. Thus, the user can receive these benefits without doing the work themselves.
Disadvantages of inheritance.
Even though Inheritance is the key concept of object-oriented programming and provides many advantages, it also suffers from many limitations. The following are the limitations of Inheritance.
1. Increases Program Complexity: Although Inheritance is generally recommended as a solution for complicated projects, overuse or improper use of Inheritance can simply increase the complexity and reduces the understandability.
2. Improper utilization of memory: In Inheritance, certain members in the base class are not used at all. However, memory is allocated to them. Thus, there is improper utilization of memory for certain members of the base class.
3. Extra time needed for understanding class libraries: In some situations, reusing a complex library in your program may require extra time to understand its interfaces and correct usage of the libraries’ classes, which slows down your initial design and coding. So it is better to write all the necessary code by yourself to understand exactly how it works.
4. Compiler overheads: Invoking member functions of the classes involved in Inheritance creates more compiler overheads and increases execution time than the invocation of simple functions. However, it can be compromised against the large benefits of Inheritance.
5. Proper understanding of hierarchy: Deriving new classes from existing classes is not always as straight forward as it might initially appear. Mistakes in an inheritance hierarchy can cripple an object model, so deep understanding of Inheritance and its effects are crucial.