Inheritance in C++
Inheritance in C++
The class hierarchy can be as deep as needed. The Instance variables and methods are inherited
down through the levels and can be redefined according to the requirement in a subclass. In
general, the further down in the hierarchy a class appears, the more specialized its behavior. When
a message is sent to an object, it is passed up the inheritance tree starting from the class of the
receiving object until a definition is found for the method. This process is called upcasting.
Consider a group of vehicles. You need to create classes for Bus, Car and
Truck. The methods fuelAmount(), capacity(), applyBrakes() will be same for all
of the 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 in
below figure:
You can clearly see that above process results in duplication of 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 rest of the three classes from base class(Vehicle).
Implementing inheritance in C++: For creating a sub-class which is inherited
from the base class we have to follow the below syntax.
Syntax:
class subclass_name : access_mode base_class_name
{
//body of subclass
};
Here, subclass_name is the name of the sub class, access_mode is the mode
in which you want to inherit this sub class for example: public, private etc.
and base_class_name is the name of the base class from which you want to
inherit the sub 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.
// C++ program to demonstrate implementation
// of Inheritance
//Base class
class Parent
{
public:
int id_p;
};
// Sub class inheriting from Base Class(Parent)
class Child : public Parent
{
public:
int id_c;
};
//main function
int main()
{
Child obj1;
// An object of class child has all data members
// and member functions of class parent
obj1.id_c = 7;
obj1.id_p = 91;
cout << "Child id is " << obj1.id_c << endl;
cout << "Parent id is " << obj1.id_p << endl;
return 0;
}
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’.
Modes of Inheritance
1. Public mode: If we derive a sub class 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 derived class.
2. Protected mode: If we derive a sub class from a Protected base class. Then
both public member and protected members of the base class will become
protected in derived class.
3. Private mode: If we derive a sub class from a Private base class. Then both
public member and protected members of the base class will become
Private in 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 below
example. It is just question of access.
// C++ Implementation to show that a derived class
// doesn’t inherit access to private data members.
// However, it does inherit a full parent object
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
};
class D : private A // 'private' is default for classes
{
// x is private
// y is private
// z is not accessible from D
};
The below table summarizes the above three modes and shows the access
specifier of the members of base class in the sub class when derived in public,
protected and private modes:
Syntax:
class subclass_name : access_mode base_class
{
//body of subclass
};
Output
This is a Vehicle
2. Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class
can inherit from more than one classes. i.e one sub class is inherited from
more than one base classes.
Syntax:
Output
This is a Vehicle
This is a 4 wheeler Vehicle
Please visit this link to learn multiple inheritance in details.
3. Multilevel Inheritance: In this type of inheritance, a derived class is created
from another derived class.
Output
This is a Vehicle
Objects with 4 wheels are vehicles
Car has 4 Wheels
4. Hierarchical Inheritance: In this type of inheritance, more than one sub
class is inherited from a single base class. i.e. more than one derived class is
created from a single base class.
Output
This is a Vehicle
This is a Vehicle
Output
This is a Vehicle
Fare of Vehicle
6. A special case of hybrid inheritance : Multipath inheritance:
A derived class with two base classes and these two base classes have one
common base class is called multipath inheritance. An ambiguity can arrise in
this type of inheritance.
Consider the following program:
// C++ program demonstrating ambiguity in Multipath
// Inheritance
#include <conio.h>
#include <iostream.h>
class ClassA {
public:
int a;
};
class ClassB : public ClassA {
public:
int b;
};
class ClassC : public ClassA {
public:
int c;
};
class ClassD : public ClassB, public ClassC {
public:
int d;
};
void main()
{
ClassD obj;
// obj.a = 10; //Statement 1, Error
// obj.a = 100; //Statement 2, Error
obj.ClassB::a = 10; // Statement 3
obj.ClassC::a = 100; // Statement 4
obj.b = 20;
obj.c = 30;
obj.d = 40;
cout << "\n A from ClassB : " << obj.ClassB::a;
cout << "\n A from ClassC : " << obj.ClassC::a;
cout << "\n B : " << obj.b;
cout << "\n C : " << obj.c;
cout << "\n D : " << obj.d;
}
Output:
A from ClassB : 10
A from ClassC : 100
B : 20
C : 30
D : 40
In the above example, both ClassB & ClassC inherit ClassA, they both have
single copy of ClassA. However ClassD inherit both ClassB & ClassC, therefore
ClassD have two copies of ClassA, one from ClassB and another from ClassC.
If we need to access the data member a of ClassA through the object of
ClassD, we must specify the path from which a will be accessed, whether it is
from ClassB or ClassC, bco’z compiler can’t differentiate between two copies of
ClassA in ClassD.
There are 2 ways to avoid this ambiguity:
Avoiding ambiguity using scope resolution operator:
Using scope resolution operator we can manually specify the path from which
data member a will be accessed, as shown in statement 3 and 4, in the above
example.
obj.ClassB::a = 10; //Statement 3
obj.ClassC::a = 100; //Statement 4
Output:
A : 100
B : 20
C : 30
D : 40
According to the above example, ClassD has only one copy of ClassA,
therefore, statement 4 will overwrite the value of a, given at statement 3.
One of the most important concepts in object-oriented programming is that of
inheritance. Inheritance allows us to define a class in terms of another class, which
makes it easier to create and maintain an application. This also provides an opportunity
to reuse the code functionality and fast implementation time.
When creating a class, instead of writing completely new data members and member
functions, the programmer can designate that the new class should inherit the
members of an existing class. This existing class is called the base class, and the new
class is referred to as the derived class.
The idea of inheritance implements the is a relationship.
For example, mammal IS-A animal, dog IS-A mammal hence dog IS-A animal as well
and so on.
// Base class
class Shape {
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
}
};
int main(void) {
Rectangle Rect;
Rect.setWidth(5);
Rect.setHeight(7);
return 0;
}
When the above code is compiled and executed, it produces the following result −
Total area: 35
A derived class inherits all base class methods with the following exceptions −
Type of Inheritance
When deriving a class from a base class, the base class may be inherited
through public, protected or private inheritance. The type of inheritance is specified
by the access-specifier as explained above.
We hardly use protected or private inheritance, but public inheritance is commonly
used. While using different type of inheritance, following rules are applied −
Public Inheritance − When deriving a class from a public base
class, public members of the base class become public members of the
derived class and protected members of the base class
become protected members of the derived class. A base
class's private members are never accessible directly from a derived class, but
can be accessed through calls to the public and protected members of the
base class.
Protected Inheritance − When deriving from a protected base
class, public and protected members of the base class
become protected members of the derived class.
Private Inheritance − When deriving from a private base
class, public and protected members of the base class
become private members of the derived class.
Multiple Inheritance
A C++ class can inherit members from more than one class and here is the extended
syntax −
class derived-class: access baseA, access baseB....
Where access is one of public, protected, or private and would be given for every
base class and they will be separated by comma as shown above. Let us try the
following example −
Live Demo
#include <iostream>
protected:
int width;
int height;
};
// Derived class
class Rectangle: public Shape, public PaintCost {
public:
int getArea() {
return (width * height);
}
};
int main(void) {
Rectangle Rect;
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
return 0;
}
When the above code is compiled and executed, it produces the following result −
Total area: 35
Total paint cost: $2450