Inheritance in CPP
Inheritance in CPP
The capability of a class to derive properties and characteristics from another class is called
Inheritance. Inheritance is one of the most important features of Object-Oriented Programming.
Inheritance is a feature or a process in which, new classes are created from the existing classes. The
new class created is called “derived class” or “child class” and the existing class is known as the
“base class” or “parent class”. The derived class now is said to be inherited from the base class.
When we say derived class inherits the base class, it means, the derived class inherits all the properties
of the base class, without changing the properties of base class and may add new features to its own.
These new features in the derived class will not affect the base class. The derived class is the
specialized class for the base class.
Sub Class: The class that inherits properties from another class is called Subclass or Derived
Class.
Super Class: The class whose properties are inherited by a subclass is called Base Class or
Superclass.
The Topic is divided into the following subtopics:
Why and when to use inheritance?
Modes of Inheritance
Types of Inheritance
Why and when to use inheritance?
Consider a group of vehicles. You need to create classes for Bus, Car, and Truck. The methods
fuelAmount(), capacity(), applyBrakes() will be the same for all three classes. If we
create these classes avoiding inheritance then we have to write all of these functions in each of the
three classes as shown below figure:
You can clearly see that the above process results in duplication of the same code 3 times. This
increases the chances of error and data redundancy. To avoid this type of situation, inheritance is
used. If we create a class Vehicle and write these three functions in it and inherit the rest of the classes
from the vehicle class, then we can simply avoid the duplication of data and increase re-usability.
Look at the below diagram in which the three classes are inherited from vehicle class:
Using inheritance, we have to write the functions only one time instead of three times as we have
inherited the rest of the three classes from the base class (Vehicle).
NAVANIT CHOUDHURY Page 1
Inheritance in C++
Implementing inheritance in C++: For creating a sub-class that is inherited from the base class we
have to follow the below syntax.
Derived Classes: A Derived class is defined as the class derived from the base class.
Syntax:
//body of class
};
Where,
class : keyword to create a new class
derived_class_name : name of the new class, which will inherit the base class
access-specifier : either of private, public or protected. If neither is specified, PRIVATE is
taken as default
base-class-name : name of the base class
Note: A derived class doesn’t inherit access to private data members. However, it does
inherit a full parent object, which contains any private members which that class
declares.
Example:
Note:
1. When a base class is privately inherited by the derived class, public members of the base class
becomes the private members of the derived class and therefore, the public members of the
base class can only be accessed by the member functions of the derived class. They are
inaccessible to the objects of the derived class.
2. On the other hand, when the base class is publicly inherited by the derived class, public
members of the base class also become the public members of the derived class. Therefore,
the public members of the base class are accessible by the objects of the derived class as well
as by the member functions of the derived class.
//MemberFunctionWithoutArgument.cpp
// Example 1: define member function without argument within the class
#include <iostream>
using namespace std;
class Person {
int id;
char name[100];
public:
void set_p() {
cout << endl <<"Enter ID and Name of Candidate" << endl;
cout << "\t ID : ";
cin >> id;
cout << "\t Name : ";
cin >> name;
}
void display_p() {
cout << endl <<"Display ID and Name of Candidate" << endl;
cout << endl <<"\t Id: "<< id << "\n\t Name: " << name << endl;
}
}; //end of class Person
public:
void set_s() {
set_p(); // call method set_p() fram class Person
cout << endl <<"Enter Course Name and Course Fees" << endl;
cout << "\t Course Name:";
cin >> course;
cout << "\t Course Fee:";
cin >> fee;
}
void display_s() {
display_p();
cout <<"\t Course: "<< course << "\n\t Fee: " << fee << endl;
}
}; //end of class Student (Drive Class of Person)
int main() {
Student s; // Object s of class Student
s.set_s(); // Call method set_s() from class student
s.display_s(); // Call method Display_s() from class student
return 0;
}
Output:
Enter the Id: 101
Enter the Name: Dev
Enter the Course Name: GCS
Enter the Course Fee:70000
Id: 101
Name: Dev
Course: GCS
// MemberFunctionWithoutArgumenOutsideClass.cpp
// Example 2. define member function without argument outside the class
#include<iostream>
using namespace std;
class Person {
int id;
char name[100];
public:
void set_p();
void display_p();
}; //end of class Person
void Person::display_p() {
cout << endl <<"Display ID and Name of Candidate" << endl;
cout << endl <<"\t Id: "<< id << "\n\t Name: " << name << endl;
}
// end of methods implementation of class Person.
public:
void set_s();
void display_s();
}; // end of sub class Student
void Student::display_s() {
display_p(); // call method dispaly_p() from class Person
cout <<"\t Course: "<< course << "\n\t Fee: " << fee << endl;
}
// end of methods implementation of sub class Student.
// mai function
int main() {
Student s; // Object s of class Student
s.set_s(); // Call method set_s() from class student
s.display_s(); // Call method Display_s() from class student
return 0;
}
Output:
Enter the Id: 101
Enter the Name: Dev
Enter the Course Name: GCS
Enter the Course Fee: 70000
Id: 101
Name: Dev
Course: GCS
Fee: 70000
class Person {
int id;
char name[100];
public:
void set_p(int, char[]);
void display_p();
};
void Person::display_p() {
cout << endl << id << "\t" <<name;
}
void Student::display_s() {
display_p();
cout << "t" << course << "\t" << fee;
}
main() {
Student s; //object of type Student
s.set_s(1001,"Ram","B.Tech",2000);
s.display_s();
return 0;
}
//ImplementationOfInheritance.cpp
// Example 4: C++ program to demonstrate implementation of Inheritance
#include <bits/stdc++.h>
using namespace std;
// Base class
class Parent {
public:
int id_p;
};
// main function
int main() {
Child obj1;
return 0;
}
Output
Child id is: 7
Parent id is: 91
Output:
Child id is: 7
Parent id is: 91
In the above program, the ‘Child’ class is publicly inherited from the ‘Parent’ class so the public data
members of the class ‘Parent’ will also be inherited by the class ‘Child’.
1. Public Mode: If we derive a subclass from a public base class. Then the public member of the
base class will become public in the derived class and protected members of the
base class will become protected in the derived class.
2. Protected Mode: If we derive a subclass from a Protected base class. Then both public members
and protected members of the base class will become protected in the derived
class.
Note: The private members in the base class cannot be directly accessed in the derived class, while
protected members can be directly accessed. For example, Classes B, C, and D all contain the
variables x, y, and z in the below example. It is just a question of access.
class A {
public:
int x;
protected:
int y;
private:
int z;
};
class B : public A {
// x is public
// y is protected
// z is not accessible from B
};
class C : protected A {
// x is protected
// y is protected
// z is not accessible from C
};
The below table summarizes the above three modes and shows the access specifier of the members of
the base class in the subclass when derived in public, protected and private modes:
Types Of Inheritance:
1. Single inheritance
2. Multilevel inheritance
1. Single Inheritance: In single inheritance, a class is allowed to inherit from only one class. i.e. one
subclass is inherited by one base class only.
Syntax:
class subclass_name : access_mode base_class {
// body of subclass
};
OR
//SingleInheritance.cpp
// Example 6 : C++ program to explain Single inheritance
#include <iostream>
using namespace std;
// base class
class Vehicle {
public:
Vehicle() { //base class constructor
cout << "This is a Vehicle\n"; //base class output
}
};
};
// 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
// SingleInheritance01.cpp
// Example 7: Protected data member and accessing methods
// without arguments
#include<iostream>
using namespace std;
class A {
protected:
int a; // data members of class A
public:
void set_A() {
cout<<"Enter the Value of a for class A = ";
cin >> a; // read value of a from KB
}
void disp_A() {
cout << endl << "Value of a for class A = " << a;
}
}; //end of class A (base class)
class B: public A {
int b, p; // data members of class A
public:
void set_B() {
set_A(); // call method from base class A
cout << "Enter the Value of b for class B = ";
cin >> b; // read value of a from KB
}
void disp_B() {
disp_A(); // call method from base class A
cout << endl << "Value of b of class B = " << b;
}
void cal_product() {
p = a * b;
cout << endl << "Product of " << a << " * "
<< b << " = " << p;
}
}; //end of sub class B
// main function
main() {
B obj_b; // drive class object
obj_b.set_B(); // call method of drive class
obj_b.cal_product(); // call method of drive class
return 0;
}
Output:
Enter the Value of A= 3 3
Enter the Value of B= 5 5
Product of 3 * 5 = 15
// SingleInheritance02.cpp
// Example 8 : Protected data member and accessing methods
// with argument
#include<iostream>
using namespace std;
class A {
protected:
int a; // data members
public:
void set_A(int x) {
a = x; // set the value of a
}
void disp_A() {
cout << endl << "Value of a of class A = "
<< a; //display value of a
}
}; //end of class A
class B: public A {
int b, p; // data members drive class B
public:
void set_B(int x, int y) {
set_A(x); // set the value of a of base class A
b = y; // Set the value of b of class B
}
void disp_B() {
disp_A(); //display data of class A (base class)
cout << endl << "Value of b of class B = " << b; //
print data member of class B
}
void cal_product() {
p = a * b;
cout << endl << "Product of data member of class A &
Drive Class B = "
<< a << " * " << b << " = " << p;
}
}; // end of class B (derived class of A)
main() {
B obj_b; // object b from derive class B
obj_b.set_B(4,5); // method from derived class B to set
// data member
// _b.disp_A(); // method from derived class A to
// display data member a
obj_b.disp_B(); // method from derived class B to set
// data member b
obj_b.cal_product(); // method from derived class B
// to cal product
return 0;
}
Output
Product of 4 * 5 = 20
2. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class can inherit from
more than one class. i.e one subclass is inherited from more than one base class.
Syntax:
Here, the number of base classes will be separated by a comma (‘, ‘) and the access mode for
every base class must be specified.
// MultipleInheritance.cpp
// Example 9 : C++ program to explain multiple inheritance
#include <iostream>
using namespace std;
}; //
// main function
int main() {
// Creating object of sub class will invoke
// the constructor of base classes.
Vehicle obj_V;
cout << endl;
// Car obj_C;
FourWheeler obj_FW;
cout << endl;
Car obj_C;
return 0;
}
Output
This is a Vehicle
This is a 4 wheeler Vehicle
// MultipleInheritance01.cpp
// Example 10 : C++ program to explain multiple inheritance
// with protected member, method without argument
#include<iostream>
using namespace std;
class A {
protected:
int a; // data member
public:
void set_A() {
cout << "Enter the Value of a of class A : ";
cin >> a; // read data member
}
void disp_A() {
cout << endl << "\t Value of a = " << a;
}
}; // end of class A
class B: public A {
protected:
int b; // data member
public:
void set_B() {
void disp_B() {
cout << endl << "\t Value of b = "<<b;
}
}; // end of sub class A (drive class of A)
class C: public B {
int c, p; // data members
public:
void set_C() {
cout << "Enter the Value of c for class C : ";
cin >> c; // read data member
}
void disp_C() {
cout << endl << "\t Value of c = " << c;
}
void cal_product() {
p = a * b * c;
cout << endl << "\t Product of Data Members "
<< a << " * " << b << " * " << c << " = " << p;
}
}; // end of sub class C (drive class of B)
// main function
main() {
C obj_c;
obj_c.set_A();
obj_c.set_B();
obj_c.set_C();
obj_c.disp_A();
obj_c.disp_B();
obj_c.disp_C();
obj_c.cal_product();
return 0;
}
3. Multilevel Inheritance: In this type of inheritance, a derived class is created from another
derived class.
class C {
... ..
...
};
class B: public C {
... ..
...
};
class A: public B {
... ...
...
};
// MultilevelInheritance.cpp
// example 11: C++ program to implement Multilevel Inheritance
#include <iostream>
using namespace std;
// base class
class Vehicle {
public:
Vehicle() {
cout << "\t Executing constructor Vehicle\n";
}
}; //end of base class Vehicle
// main function
int main() {
// Creating object of sub class will invoke
// the constructor of base classes.
Vehicle obj_V;
cout << endl;
fourWheeler obj_fw;
cout << endl;
Car obj;
cout << endl;
return 0;
}
Output
Syntax:
class A {
class B : public A {
// body of class B.
}
class C : public A {
// body of class C.
}
class D : public A {
// HierarchicalInheritance.cpp
// Example 12: C++ program to implement Hierarchical Inheritance
#include <iostream>
using namespace std;
// base class
class Vehicle {
public:
Vehicle() {
cout << "\n\t Executing constructor Vehicle\n";
}
}; //end of class Vehicle
// main function
int main() {
// creating object of sub class will
// invoke the constructor of base class.
Car obj1;
Bus obj2;
return 0;
}
Output
This is a Vehicle
This is a Vehicle
5. Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by combining more than one
type of inheritance. For example: Combining Hierarchical inheritance and Multiple Inheritance.
// HybridInheritance.cpp
// Example 13 : C++ program for Hybrid Inheritance
#include <iostream>
using namespace std;
// base class
class Vehicle {
public:
Vehicle() { cout << "This is a Vehicle\n"; }
};
// base class
class Fare {
public:
Fare() { cout << "Fare of Vehicle\n"; }
};
// 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
// Example 14:
#include <iostream>
using namespace std;
class A {
protected:
int a;
public:
void get_a() {
cout << "Enter the value of 'a' : ";
cin>>a;
}
};
class B : public A {
protected:
int b;
public:
void get_b() {
cout << "Enter the value of 'b' : ";
cin >> b;
}
};
class C {
protected:
int c;
public:
void get_c() {
cout << "Enter the value of c is : ";
cin >> c;
}
};
public:
void mul() {
get_a();
get_b();
get_c();
cout << "Multiplication of a, b, c is : " << a * b * c;
}
};
//main program
int main() {
D d;
d.mul();
return 0;
}
A derived class with two base classes and these two base classes have one common base class is
called multipath inheritance. Ambiguity can arise in this type of inheritance.
Example:
// AmbiguityMultipathInheritance.cpp
//Example 15: C++ program demonstrating ambiguity in Multipath Inheritance
#include <iostream>
using namespace std;
class ClassA {
public:
int a;
}; //end of class ClassA
int main() {
ClassD obj;
// obj.a = 10; // Statement 1, Error
// obj.a = 100; // Statement 2, Error
obj.b = 20;
obj.c = 30;
obj.d = 40;
Output
a from ClassB : 10
a from ClassC : 100
b : 20
c : 30
d : 40
Output:
a from ClassB : 10
a from ClassC : 100
b : 20
c : 30
d : 40
In the above example, both ClassB and ClassC inherit ClassA, they both have a single copy of
ClassA. However Class-D inherits both ClassB and Class , therefore Class-D has two copies of Class
A, one from Class B and another from Class C.
If we need to access the data member of Class A through the object of Class-D, we must specify the
path from which a will be accessed, whether it is from Class B or Class C, bcoz’ compiler can’t
differentiate between two copies of Class A in Class-D.
1) Avoiding ambiguity using the scope resolution operator: Using the scope resolution operator we
can manually specify the path from which data member a will be accessed, as shown in statements 3
and 4, in the above example.
class ClassA {
public:
int a;
};
};
int main() {
ClassD obj;
obj.b = 20;
obj.c = 30;
obj.d = 40;
Output:
a : 100
b : 20
c : 30
d : 40
According to the above example, Class-D has only one copy of ClassA, therefore, statement 4 will
overwrite the value of a, given in statement 3.