You are on page 1of 16

Inheritance in C++

In C++, inheritance is a process in which one object acquires all the properties and behaviours
of its parent object automatically. In such way, you can reuse, extend or modify the attributes
and behaviours which are defined in other class.

In C++, the class which inherits the members of another class is called derived class and the
class whose members are inherited is called base class. The derived class is the specialized
class for the base class.

Advantage of C++ Inheritance

Code reusability: Now you can reuse the members of your parent class. So, there is no need to
define the member again. So less code is required in the class.

What is a Derived class

A Derived class is defined as the class derived from the base class.

The Syntax of Derived class:

class derived_class_name :: visibility-mode base_class_name


{
// body of the derived class.
}

Where,

derived_class_name: It is the name of the derived class.

visibility mode: The visibility mode specifies whether the features of the base class are publicly
inherited or privately inherited. It can be public or private.

base_class_name: It is the name of the base class.

o When the base class is privately inherited by the derived class, public members of the base
class becomes the private members of the derived class. Therefore, the public members of the
base class are not accessible by the objects of the derived class only by the member functions
of the derived class.
o 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 base class.
Note

o In C++, the default mode of visibility is private.


o The private members of the base class are never inherited.

Types Of Inheritance

C++ supports five types of inheritance:

o Single inheritance
o Multiple inheritance
o Hierarchical inheritance
o Multilevel inheritance
o Hybrid inheritance

C++ Single Inheritance

Single inheritance is defined as the inheritance in which a derived class is inherited from the only one
base class.

Where 'A' is the base class, and 'B' is the derived class.

When one class inherits another class, it is known as single level inheritance. Let's see the example
of single level inheritance which inherits the fields only.

Let's see a simple example.


#include <iostream>
using namespace std;

class A
{
int a = 4;
int b = 5;
public:
int mul()
{
int c = a*b;
return c;
}
};

class B : private A
{
public:
void display()
{
int result = mul();
cout <<"Multiplication of a and b is : "<<result<< endl;
}
};
int main()
{
B b;
b.display();

return 0;
}

OUTPUT
Multiplication of a and b is : 20

In the above example, class A is privately inherited. Therefore, the mul() function of class 'A' cannot
be accessed by the object of class B. It can only be accessed by the member function of class B.

Let us see another example where data members are declared as public:
#include <iostream>
using namespace std;
class Account
{
public:
float salary = 60000;
};
class Programmer: public Account
{
public:
float bonus = 5000;
};

int main() {
Programmer p1;
cout<<"Salary: "<<p1.salary<<endl;
cout<<"Bonus: "<<p1.bonus<<endl;
return 0;
}

Output:
Salary: 60000
Bonus: 5000
How to make a Private Member Inheritable

The private member is not inheritable. If we modify the visibility mode by making it public, but this
takes away the advantage of data hiding.

C++ introduces a third visibility modifier, i.e., protected. The member which is declared as protected
will be accessible to all the member functions within the class as well as the class immediately derived
from it.

Visibility modes can be classified into three categories:

o Public: When the member is declared as public, it is accessible to all the functions of the
program.
o Private: When the member is declared as private, it is accessible within the class only.
o Protected: When the member is declared as protected, it is accessible within its own class as
well as the class immediately derived from it.

Visibility of Inherited Members

C++ Multilevel Inheritance

Multilevel inheritance is a process of deriving a class from another derived class.


C++ Multi Level Inheritance Example

When one class inherits another class which is further inherited by another class, it is known as multi
level inheritance in C++. Inheritance is transitive so the last derived class acquires all the members of
all its base classes.

Let's see the example of multi level inheritance in C++.

#include <iostream>
using namespace std;

class Animal {
public:
void eat() {
cout<<"Eating..."<<endl;
}
};
class Dog: public Animal
{
public:
void bark(){
cout<<"Barking..."<<endl;
}
};
class Puppy: public Dog
{
public:
void play() {
cout<<"Playing...";
}
};

int main()
{
Puppy d1;
d1.eat();
d1.bark();
d1.play();
return 0;
}

OUTPUT
Eating...
Barking...
Playing...

C++ Multiple Inheritance

Multiple inheritance is the process of deriving a new class that inherits the attributes from two or more
classes.
Let's see a simple example of multiple inheritance.
#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
void get_a(int n)
{
a = n;
}
};

class B
{
protected:
int b;
public:
void get_b(int n)
{
b = n;
}
};
class C : public A,public B
{
public:
void display()
{
cout << "The value of a is : " <<a<< endl;
cout << "The value of b is : " <<b<< endl;
cout<<"Addition of a and b is : "<<a+b;
}
};
int main()
{
C c;
c.get_a(10);
c.get_b(20);
c.display();

return 0;
}

OUTPUT:
The value of a is : 10
The value of b is : 20
Addition of a and b is : 30
Ambiquity Resolution in Inheritance

Ambiguity can be occurred in using the multiple inheritance when a function with the same name occurs
in more than one base class.

Let's understand this through an example:

#include <iostream>
using namespace std;
class A
{
public:
void display()
{
cout << "Class A" << endl;
}
};
class B
{
public:
void display()
{
cout << "Class B" << endl;
}
};
class C : public A, public B
{
void view()
{
display();
}
};
int main()
{
C c;
c.display();
return 0;
}

OUTPUT
error: reference to 'display' is ambiguous
display();

The above issue can be resolved by using the class resolution operator with the function. In the above
example, the derived class code can be rewritten as:

class C : public A, public B


{
void view()
{
A :: display(); // Calling the display() function of class A.
B :: display(); // Calling the display() function of class B.

}
};
So the corrected program is
#include <iostream>
using namespace std;
class A
{
public:
void display()
{
cout << "Class A" << endl;
}
};
class B
{
public:
void display()
{
cout << "Class B" << endl;
}
};

class C : public A, public B


{
public:
void view()
{
A::display(); // Calling the display() function of class A.
B::display(); // Calling the display() function of class B.

}
};

int main()
{
C c;
c.view();
c.B::display();
return 0;
}

OUTPUT
Class A
Class B
Class B

C++ Hybrid Inheritance

Hybrid inheritance is a combination of more than one type of inheritance.


Let's see a simple example:
#include <iostream>
using namespace std;
class A
{
protected:
int a;
public:
void get_a()
{
cout << "Enter the value of 'a' : " << endl;
cin>>a;
}
};

class B : public A
{
protected:
int b;
public:
void get_b()
{
cout << "Enter the value of 'b' : " << endl;
cin>>b;
}
};
class C
{
protected:
int c;
public:
void get_c()
{
cout << "Enter the value of c is : " << endl;
cin>>c;
}
};

class D : public B, public C


{
protected:
int d;
public:
void mul()
{
get_a();
get_b();
get_c();
cout << "Multiplication of a,b,c is : " <<a*b*c<< endl;
}
};
int main()
{
D d;
d.mul();
return 0;
}

OUTPUT
Enter the value of 'a' :
10
Enter the value of 'b' :
20
Enter the value of c is :
30
Multiplication of a,b,c is : 6000

C++ Hierarchical Inheritance

Hierarchical inheritance is defined as the process of deriving more than one class from a base class.

Syntax of Hierarchical inheritance:


class A
{
// body of the class A.
}
class B : public A
{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}
Let's see a simple example:
#include <iostream>
using namespace std;
class Shape // Declaration of base class.
{
public:
int a;
int b;
void get_data(int n,int m)
{
a= n;
b = m;
}
};
class Rectangle : public Shape // inheriting Shape class
{
public:
int rect_area()
{
int result = a*b;
return result;
}
};
class Triangle : public Shape // inheriting Shape class
{
public:
int triangle_area()
{
float result = 0.5*a*b;
return result;
}
};
int main()
{
Rectangle r;
Triangle t;
int length,breadth,base,height;
cout << "Enter the length and breadth of a rectangle: " << endl;
cin>>length>>breadth;
r.get_data(length,breadth);
int m = r.rect_area();
cout << "Area of the rectangle is : " <<m<< endl;
cout << "Enter the base and height of the triangle: " << endl;
cin>>base>>height;
t.get_data(base,height);
float n = t.triangle_area();
cout <<"Area of the triangle is : " << n<<endl;
return 0;
}

OUTPUT
Enter the length and breadth of a rectangle:
23
20
Area of the rectangle is : 460
Enter the base and height of the triangle:
2
5
Area of the triangle is : 5
Virtual Base class

Virtual base classes are used in virtual inheritance in a way of preventing multiple
“instances” of a given class appearing in an inheritance hierarchy when using multiple
inheritances.
Need for Virtual Base Classes:
Consider the situation where we have one class A .This class is A is inherited by two other
classes B and C. Both these class are inherited into another in a new class D as shown in
figure below.

As we can see from the figure that data members/function of class A are inherited twice to
class D. One through class B and second through class C. When any data / function
member of class A is accessed by an object of class D, ambiguity arises as to which
data/function member would be called? One inherited through B or the other inherited
through C. This confuses compiler and it displays error.

Example: To show the need of Virtual Base Class in C++

#include <iostream>
using namespace std;

class A {
public:
void show()
{
cout << "Hello form A \n";
}
};

class B : public A {
};

class C : public A {
};

class D : public B, public C {


};
int main()
{
D object;
object.show();
}

Compile Errors:
prog.cpp: In function 'int main()':
prog.cpp:29:9: error: request for member 'show' is ambiguous
object.show();
^
prog.cpp:8:8: note: candidates are: void A::show()
void show()
^
prog.cpp:8:8: note:

How to resolve this issue?


To resolve this ambiguity when class A is inherited in both class B and class C, it is
declared as virtual base class by placing a keyword virtual as :
Syntax for Virtual Base Classes:
Syntax 1:
class B : virtual public A
{
};

Syntax 2:
class C : public virtual A
{
};

Note: virtual can be written before or after the public. Now only one copy of data/function
member will be copied to class C and class B and class A becomes the virtual base class.
Virtual base classes offer a way to save space and avoid ambiguities in class hierarchies
that use multiple inheritances. When a base class is specified as a virtual base, it can act as
an indirect base more than once without duplication of its data members. A single copy of its
data members is shared by all the base classes that use virtual base.

Corrected program would be:


#include <iostream>
using namespace std;

class A {
public:
void show()
{
cout << "Hello form A \n";
}
};

class B : virtual public A {


};
class C : public virtual A {
};

class D : public B, public C {


};

int main()
{
D object;
object.show();
}

OUTPUT
Hello from A

Containership in C++ (Alternative way to Inherit)


We can create an object of one class into another and that object will be a member of the
class. This type of relationship between classes is known
as containership or has_a relationship as one class contain the object of another class.
And the class which contains the object and members of another class in this kind of
relationship is called a container class.
The object that is part of another object is called contained object, whereas object
that contains another object as its part or attribute is called container object.
Difference between containership and inheritance
Containership
-> When features of existing class are wanted inside your new class, but, not its interface
for eg->
1)computer system has a hard disk
2)car has an Engine, chassis, steering wheels.
Inheritance
-> When you want to force the new type to be the same type as the base class.
for eg->
1)computer system is an electronic device
2)Car is a vehicle

Syntax for Containership:


// Class that is to be contained
class first {
.
.
};

// Container class
class second {

// creating object of first


first f;
.
.
};
Below examples explain the Containership in C++ in a better way
#include <iostream>
using namespace std;

class first {
public:
void showf()
{
cout << "Hello from first class\n";
}
};

// Container class
class second {
// creating object of first
first f;

public:
// constructor
second()
{
// calling function of first class
f.showf();
}
};

int main()
{
// creating object of second
second s;
}

Output:
Hello from first class

Explanation:In the class second we have an object of class first. This is another type of
inheritance we are witnessing. This type of inheritance is known as has_a relationship as
we say that class second has an object of first class first as its member. From the object f
we call the function of class first.
#include <iostream>
using namespace std;

class first {
public:
first()
{
cout << "Hello from first class\n";
}
};

// Container class
class second {
// creating object of first
first f;
public:
// constructor
second()
{
cout << "Hello from second class\n";
}
};

int main()
{
// creating object of second
second s;
}

Output:
Hello from first class
Hello from second class

Explanation:In this program we have not inherited class first into class second but as we
are having an object of class first as a member of class second. So when default
constructor of class second is called, due to presence of object f of first class in second,
default constructor of class first is called first and then default constructor of
class second is called.

You might also like