C++ Inheritance
Note: try all programs using http://cpp.sh/
Inheritance
in Object Oriented Programming can be described as a process of creating new
classes from existing classes.
New
classes inherit some of the properties and behavior of
the existing classes. An existing class that is "parent" of a new
class is called a base class.
New class that inherits properties of the base class is called a derived class.
Inheritance
is a technique of code reuse. It also provides possibility to extend existing
classes by creating derived classes.
The technique of deriving a new class from an old one is
called inheritance. The old class is referred to as base class and the new
class is referred to as derived class or subclass. Inheritance concept allows
programmers to define a class in terms of another class, which makes creating
and maintaining application easier. When writing a new class, instead of
writing new data member and member functions all over again, programmers can
make a bonding of the new class with the old one that the new class should
inherit the members of the existing class. A class can get derived from one or
more classes, which means it can inherit data and functions from multiple base
classes.
The
basic syntax of inheritance is:
class DerivedClass : accessSpecifier BaseClass
Access
specifier can be public, protected and private. The default access specifier
is private. Access
specifiers affect accessibility of data members of base class from the derived
class. In addition, it determines the accessibility of data members of base
class outside the derived class.
Access specifiers in
inheritance
This
inheritance mode is used mostly. In this the protected member of Base class becomes
protected members of Derived class and public becomes public.
class DerivedClass : public BaseClass
Accessing Base class members |
Public |
protected |
private |
From Base class |
Yes |
Yes |
Yes |
From object of a Base class |
Yes |
No |
No |
From Derived classes |
Yes (As Public) |
Yes (As Protected) |
No |
From object of a Derived class |
Yes |
No |
No |
From Derived class of Derived Classes |
Yes (As Public) |
Yes (As Protected) |
No |
Derived
class of Derived Classes: If we are inheriting a derived class using a
public inheritance as shown below
class B :
public A
class C :
public B
then
public and protected members of class A will be accessible in class C as public
and protected respectively.
In protected
mode, the public and protected members of Base class becomes protected members
of Derived class.
class DerivedClass : protected BaseClass
Accessing Base class members |
public |
protected |
private |
From Base class |
Yes |
Yes |
Yes |
From object of a Base class |
Yes |
No |
No |
From Derived classes |
Yes (As Protected) |
Yes (As Protected) |
No |
From object of a Derived class |
No |
No |
No |
From Derived class of Derived Classes |
Yes (As Protected) |
Yes (As Protected) |
No |
Derived
class of Derived Classes: If we are inheriting a derived class using a
protected inheritance as shown below
class B :
protected A
class C :
protected B
then
public and protected members of class A will be accessible in class C as
protected
In
private mode the public and protected members of Base class become private
members of Derived class.
class DerivedClass : private BaseClass
class DerivedClass : BaseClass // By default inheritance is private
Accessing Base class members |
public |
protected |
private |
From Base class |
Yes |
Yes |
Yes |
From object of a Base class |
Yes |
No |
No |
From Derived classes |
Yes (As Private) |
Yes (As Private) |
No |
From object of a Derived class |
No |
No |
No |
From Derived class of Derived Classes |
No |
No |
No |
Derived
class of Derived Classes: If we are inheriting a derived class using a
private inheritance as shown below
class B :
private A
class C :
private B
then
public and protected members of class A will not be accessible in class C.
Types of inheritance
C++ offers five types of
Inheritance. They are:
·
Single
Inheritance
·
Multiple
Inheritance
·
Hierarchical
Inheritance
·
Multilevel
Inheritance
·
Hybrid
Inheritance (also known as Virtual Inheritance)
In single inheritance, there is only
one base class and one derived class. The Derived class gets inherited from its
base class. This is the simplest form of inheritance. In the above figure,
fig(a) is the diagram for single inheritance.
Syntax:
class subclass_name
: access_mode base_class
{
//body of
subclass
};
//
C++ program to explain //
Single inheritance #include
<iostream> using
namespace std; //
base class class
Vehicle { public: Vehicle() { cout << "This is a Vehicle" << endl; } }; //
sub class derived from two base classes class
Car: public Vehicle{ }; //
main function int
main() {
//
creating object of sub class will //
invoke the constructor of base classes Car
obj; return
0; } |
Output:
This is a vehicle
In this type of inheritance, a single
derived class may inherit from two or more base classes. In the above list of
figures, fig(b) is the structure of Multiple Inheritance.
Program for Multiple Inheritance:
Example:
#include <iostream>
using namespace std;
class stud {
protected:
int roll, m1, m2;
public:
void get()
{
cout << "Enter the Roll No.: "; cin >> roll;
cout << "Enter the two highest marks: "; cin >> m1 >> m2;
}
};
class extracurriculam {
protected:
int xm;
public:
void getsm()
{
cout << "\nEnter the mark for Extra Curriculam Activities: "; cin >> xm;
}
};
class output : public stud, public extracurriculam {
int tot, avg;
public:
void display()
{
tot = (m1 + m2 + xm);
avg = tot / 3;
cout << "\n\n\tRoll No : " << roll << "\n\tTotal : " << tot;
cout << "\n\tAverage : " << avg;
}
};
int main()
{
output O;
O.get();
O.getsm();
O.display();
}
Output:
In this type of inheritance, multiple
derived classes get inherited from a single base class. In the above list of
figures, fig(c) is the structure of Hierarchical Inheritance.
Syntax:
class base_classname {
properties;
methods;
};
class derived_class1 : visibility_mode base_classname {
properties;
methods;
};
class derived_class2 : visibility_mode base_classname {
properties;
methods;
};
... ... ...
... ... ...
class derived_classN : visibility_mode base_classname {
properties;
methods;
};
Example:
#include <iostream>
#include <string.h>
using namespace std;
class member {
char gender[10];
int age;
public:
void get()
{
cout << "Age: "; cin >> age;
cout << "Gender: "; cin >> gender;
}
void disp()
{
cout << "Age: " << age << endl;
cout << "Gender: " << gender << endl;
}
};
class stud : public member {
char level[20];
public:
void getdata()
{
member::get();
cout << "Class: "; cin >> level;
}
void disp2()
{
member::disp();
cout << "Level: " << level << endl;
}
};
class staff : public member {
float salary;
public:
void getdata()
{
member::get();
cout << "Salary: Rs."; cin >> salary;
}
void disp3()
{
member::disp();
cout << "Salary: Rs." << salary << endl;
}
};
int main()
{
member M;
staff S;
stud s;
cout << "Student" << endl;
cout << "Enter data" << endl;
s.getdata();
cout << endl
<< "Displaying data" << endl;
s.disp();
cout << endl
<< "Staff Data" << endl;
cout << "Enter data" << endl;
S.getdata();
cout << endl
<< "Displaying data" << endl;
S.disp();
}
Output:
The classes can also be derived from
the classes that are already derived. This type of inheritance is called
multilevel inheritance.
Example:
#include <iostream>
using namespace std;
class base {
public:
void display1()
{
cout << "\nBase class content.";
}
};
class derived : public base {
public:
void display2()
{
cout << "1st derived class content.";
}
};
class derived2 : public derived {
void display3()
{
cout << "\n2nd Derived class content.";
}
};
int main()
{
derived2 D;
//D.display3();
D.display2();
D.display1();
}
Output:
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. In the above figure, the fig(5)
is the diagram for Hybrid inheritance.
// C++ program for Hybrid Inheritance
#include <iostream>
using namespace std;
// base class
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
//base class
class Fare
{
public:
Fare()
{
cout<<"Fare of Vehicle\n";
}
};
// first sub class
class Car: public Vehicle
{
};
// second sub class
class Bus: public Vehicle, public Fare
{
};
// main function
int main()
{
// creating
object of sub class will
// invoke the
constructor of base class
Bus obj2;
return 0;
}
Output:
This is a Vehicle
Fare of Vehicle
When you have a
hybrid inheritance then a Diamond problem may arise. In this problem a Derived
class will have multiple paths to a Base class. This will result in duplicate
inherited members of the Base class. This kind of problem is known as Diamond problem
When a default or
parameterized constructor of a derived class is called, the default constructor
of a base class is called automatically. As you create an object of a derived
class, first the default constructor of a base class is called after that
constructor of a derived class is called.
To call
parameterized constructor of a base class you need to call it explicitly as
shown below.
Student(string szName, int iYear, string szUniversity) :Person(szName, iYear) { } |
Below program
will show the order of execution that the default constructor of base class
finishes first after that the constructor of a derived class starts. For
example, there are two classes with single inheritance:
//base class class Person { public: Person() { cout <<
"Default constructor of base class called" << endl; } Person(string
lName, int year) { cout <<
"Parameterized constructor of base class called" << endl; lastName = lName; yearOfBirth = year; } string
lastName; int yearOfBirth; }; //derived class class Student :public Person { public: Student() { cout <<
"Default constructor of Derived class called" << endl; } Student(string
lName, int year, string univer) { cout <<
"Parameterized constructor of Derived class called" << endl; university = univer; } string
university; }; |
There is no
explicit call of constructor of a base class. But on creating two objects of
Student class using default and parameterized constructors, both times default
constructor of a base class get called.
Student student1; //Using default constructor of
Student class Student student2("John", 1990, "London
School of Economics"); //calling
parameterized constructor of Student class |
In both the above
cases, default constructor of a base class is called before the constructor of
a derived class.
Default constructor of base class called Default constructor of Derived class called Default constructor of base class called Parameterized constructor of Derived class called |
When multiple
inheritance is used, default constructors of base classes are called in the
order as they are in inheritance list. For example, when a constructor of
derived class is called:
class
derived: public class1, public class 2
the order of constructors calls will be
class1 default constructor class2 default constructor derived constructor |
If you want to
call a parameterized constructor of the base class then this can be done using
initializer list as shown below.
Student(string lName, int year, string univer)
:Person(lName, year) { cout << "Parameterized constructor of Derived
class works" << endl; university = univer; } |
Above code means
that you are calling parametrized constructor of the base class and passing two
parameters to it. Now the output will be
Default constructor of base class works Default constructor of Derived class works Parameterized constructor of base class works Parameterized constructor of Derived class works |
Now you can see
that parameterized constructor of the base class is called from derived class
constructor.