Inheritance in C++ with Examples

Inheritance is the process of creating new class called as derived or child class from an existing class (base/parent).It is the one of the most important feature of OOP. Inheritance uses the code reusability property of OOP.

Derived class: The class which inherits some or all the properties or traits of the base class is called derived class. We can also call it as child class because it is derived from another class.

Base class: The class from which derived class inherits the properties or traits is called as base class. It can also be called as parent class.

Why we use inheritance in C++?

Suppose, in your game, you want three characters – a magician, a cricketer and a businessman.

Since, all of the characters are persons, they can walk and talk. However, they also have some special skills. A magician can show magic, a cricketer can play cricket and a businessman can run a business.

You can individually create three classes who can walk, talk and perform their special skill as below.

Magician

  • walk
  • talk
  • show magic

Cricketer

  • walk 
  • talk
  • play cricket

Businessman

  • walk
  • talk
  • do business

In each of the classes, you would be copying the same code for walk and talk for each character.

If you want to add a new feature – sleep, you need to implement the same code for each character. This type of repetition might cause error.

It’d be a lot easier if we had a Person class with basic features like talk, walk, eat, sleep, and add special skills to those features as per our characters. This is done using inheritance.

Using inheritance, now you don’t implement the same code for walk and talk for each class. You just need to inherit them.

So, for Magician (derived class), you inherit all features of a Person (base class) and add a new feature show magic. Likewise, for a cricketer, you inherit all the features of a Person and add a new feature play cricket, and so on.

This makes your code cleaner, understandable and extendable.

Important to member: When working with inheritance, each derived class should satisfy the condition whether it “is a” base class or not. In the example above, magician is a Person, cricketer is a Person. You cannot have: Businessman is a Business.

To define derived class:

class derived:visibility_mode base_class_name

{

// statements

};

Visibility mode may be either public, private or protected. Unless the  visibility mode is specified , the mode is private by default.

Syntax: 

class base

{

// statements

};

class derived:private base

{

// statements

};

class derived1:public base

{

// statements

};

class derived2:protected base

{

// statements

};

Visibility modifier:

 

visibility mode accessible from own class accessible from derived class accessible from object outside of class
private can access cannot access cannot access
public  can access can access can access
protected can access cannot access* cannot access

*only immediately derived class can access the data

Visibility of inherited members:

base class

visibility mode

public derivation private derivation protected derivation
Private not inherited  not inherited not inherited
protected protected private protected
public public private protected
Types of inheritance:
  1. Single inheritance: When a class is derived from a single base class then it is called single inheritance.
Block Diagram

C++ single inheritance

       

Syntax:

class derived_classname: visibility_mode base_classname

{

// statements

};

Example:

// inheritance.cpp
#include <iostream> 
using namespace std; 
class base    //single base class
{
   public:
     int x;
   void getdata()
   {
     cout << "Enter the value of x = "; cin >> x;
   }
 };
class derive : public base    //single derived class
{
   private:
    int y;
   public:
   void readdata()
   {
     cout << "Enter the value of y = "; cin >> y;
   }
   void product()
   {
     cout << "Product = " << x * y;
   }
 };
 
 int main()
 {
    derive a;     //object of derived class
    a.getdata();
    a.readdata();
    a.product();
    return 0;
 }         //end of program


Output

Enter the value of x = 3
Enter the value of y = 4
Product = 12

2. Multiple inheritance: If a class is derived from two or more than two base classes then it is called as multiple inheritance.

multiple inheritance in c++

Syntax:

class derived_classname: visibility_mode base1, visibility_mode base2

{

// statements

};

Example:

  1. #include <iostream>
  2. using namespace std;
  3. class Mammal {
  4. public:
  5. Mammal()
  6. {
  7. cout << "Mammals can give direct birth." << endl;
  8. }
  9. };
  10. class WingedAnimal {
  11. public:
  12. WingedAnimal()
  13. {
  14. cout << "Winged animal can flap." << endl;
  15. }
  16. };
  17. class Bat: public Mammal, public WingedAnimal {
  18. };
  19. int main()
  20. {
  21. Bat b1;
  22. return 0;
  23. }

Output

Mammals can give direct birth.
Winged animal can flap
Ambiguity in Multiple Inheritance:

The most obvious problem with multiple inheritance occurs during function overriding.

Suppose, two base classes have a same function which is not overridden in derived class.

If you try to call the function using the object of the derived class, compiler shows error. It’s because compiler doesn’t know which function to call. For example,

  1. class base1
  2. {
  3. public:
  4. void someFunction( )
  5. { .... ... .... }
  6. };
  7. class base2
  8. {
  9. void someFunction( )
  10. { .... ... .... }
  11. };
  12. class derived : public base1, public base2
  13. {
  14. };
  15. int main()
  16. {
  17. derived obj;
  18. obj.someFunction() // Error!
  19. }
  20.  

This problem can be solved using scope resolution function to specify which function to class either base1 or base2

int main() { obj.base1::someFunction( ); // Function of base1 class is called obj.base2::someFunction(); // Function of base2 class is called. 

3. Multilevel inheritance:
There is more than one level of inheritance. A derived class from a base class acts as a base class for third class.

Syntax:
class college
{

// statements

};
class employee: public college
{

// statements

};
class academic:public employee
{

// statements

};
Example:

#include <iostream>
using namespace std;
class base //single base class
{
 	public:
 	int x;
 	void getdata()
 	{
    	cout << "Enter value of x= "; cin >> x;
 	}
};
class derive1 : public base // derived class from base class
{
 	public:
 	int y;
 	void readdata()
 	{
 	    cout << "\nEnter value of y= "; cin >> y;
 	}
};
class derive2 : public derive1   // derived from class derive1
{
 	private:
 	int z;
 	public:
 	void indata()
 	{
    	cout << "\nEnter value of z= "; cin >> z;
 	}
 	void product()
 	{
 	    cout << "\nProduct= " << x * y * z;
 	}
};
int main()
{
     derive2 a;      //object of derived class
     a.getdata();
     a.readdata();
     a.indata();
     a.product();
     return 0;
}              	//end of program

Output

Enter value of x= 2

Enter value of y= 3

Enter value of z= 3

Product= 18
 
4. Hierarchial inheritance:

If more than one class is derived from a single base class then it is called as hierarchial inheritance.

Syntax:

class employee

{

// statements

};

class academic: public employee

{

// statements

};

class non_academic: public employee

{

// statements

};

Example:

#include <iostream> 
using namespace std;

class A //single base class
{
    public:
 	int x, y;
 	void getdata()
 	{
   	    cout << "\nEnter value of x and y:\n"; cin >> x >> y;
 	}
};
class B : public A //B is derived from class base
{
    public:
 	void product()
 	{
 	    cout << "\nProduct= " << x * y;
 	}
};
class C : public A //C is also derived from class base
{
    public:
 	void sum()
 	{
        cout << "\nSum= " << x + y;
 	}
};
int main()
{
    B obj1;          //object of derived class B
    C obj2;          //object of derived class C
    obj1.getdata();
    obj1.product();
    obj2.getdata();
    obj2.sum();
    return 0;
}  //end of program


Output

Enter value of x and y:
2
3
Product= 6
Enter value of x and y:
2
3
Sum= 5
 5.Hybrid inheritance:

This is the combination of two or more types of inheritance.

C++ Multipath Inheritance

Example:

#include<iostream.h>
#include<conio.h>
class stu
{
protected:
int rno;
public:
void get_no(int a)
{
rno=a;
}
void put_no(void)
{
out<<“Roll no”<<rno<<“\n”;
}
};
class test:public stu
{
protected:
float part1,part2;
public:
void get_mark(float x,float y)
{
part1=x;
part2=y;
}
void put_marks()
{
cout<<“Marks obtained:”<<“part1=”<<part1<<“\n”<<“part2=”<<part2<<“\n”;
}
};
class sports
{
protected:
float score;
public:
void getscore(float s)
{
score=s;
}
void putscore(void)
{
cout<<“sports:”<<score<<“\n”;

}
};

class result: public test, public sports
{
float total;
public:
void display(void);
};
void result::display(void)
{
total=part1+part2+score;
put_no();
put_marks();
putscore();
cout<<“Total Score=”<<total<<“\n”;
}
int main()
{
clrscr();
result stu;
stu.get_no(123);
stu.get_mark(27.5,33.0);
stu.getscore(6.0);
stu.display();
return 0;
}

Output:

Roll no 123
Marks obtained : part1=27.5
Part2=33
Sports=6
Total score = 66.5

Function overriding:

 Function overriding is a feature that allows us to have a same function in child class which is already present in the parent class. A child class inherits the data members and member functions of parent class, but when you want to override a functionality in the child class then you can use function overriding. It is like creating a new version of an old function, in the child class.

Example:

Output
Base class    Derived Class

Leave a Reply

Insert math as
Block
Inline
Additional settings
Formula color
Text color
#333333
Type math using LaTeX
Preview
\({}\)
Nothing to preview
Insert
%d bloggers like this: