Inheritance in C++

 Inheritance in C++

The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important feature of Object Oriented Programming.

Sub Class: The class that inherits properties from another class is called Sub class or Derived Class.

Super Class:The class whose properties are inherited by sub class is called Base Class or Super class.
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 modeIf 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 modeIf 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.

Advantages of inheritance
  1. Code can be reused. 
  2. The derived class can also extend the properties of base class to generate more dominant objects. 
  3. The same base class is used for more derived classes. 
  4. When a class is derived from more than one class, the derived classes have similar properties to those of base classes. 

Disadvantages of inheritance

  • Complicated. 
  • Invoking member functions creates overhead to the compiler. 
  • In class hierarchy, various data elements remains unused, and the memory allocated to them is not utilized.
*Full Description About Inheritance
Inheritance:- Reusing the existing code without defining it again and again.

*Different types of inheritance in C++:-
1.) single inheritance
2.) multiple inheritance
3.) multilevel inheritance
4.) Hierarchical inheritance
5.) Hybrid inheritance

** C++ strongly supports the concept of Reusability. The mechanism of  deriving a new class from an old one is called ,inheritance.

-> The old class is reffered to as "Base class" or "Parent class" or "super class".

-> The new class is reffered to as "Derived class" or "child class" or "sub class".

1.) single inheritance

-> A derived class with only one base class, is known as single inheritance.

-> When a single class is derived from a single parent class, it is called Single inheritance. It is the simplest of all inheritance.

For example,

-> Car is derived from vehicle

-> Typist is derived from staff

-> Animal is derived from living things

Syntax of Single Inheritance-


class base_classname
{
    properties;
    methods;
};

class derived_classname : visibility_mode base_classname
{
    properties;
    methods;
};
Example 1:
// cpp program on single inheritance.

#include<iostream>
using namespace std;
class A
{
int a;
public:
void show()
{
cout<<" parent show";
}
};
class B: public A
{
int b;
public:
void display()
        {
cout<<"child display";
}
};
int main()
{
B b1;
b1.display();
b1.show();
return 0;
}

output:-
child display parent show
Example 2:
//cpp program to demonstrate single- inheritance.


#include<iostream>
using namespace std;
class student
{
private:
int rollno;
char name[20];
public:
void getdata()
{
cout<<"Enter roll no:";
cin>>rollno;
cout<<"Enter Name:";
cin>>name;
}
void showdata()
{
cout<<"\n roll no:"<<rollno;
cout<<"\n Name:"<<name;
}
};
class Details :public student
{
private:
int  m1,m2,m3,total;
public:
void  getmarks()
{
getdata();
cout<<"Enter marks m1,m2,m3";
cin>>m1>>m2>>m3;
}
void sum()
{
total=m1+m2+m3;
}
void display()
{
sum();
showdata();
cout<<"\n Total marks="<<total;
}
};
int main()
{
Details d;
d.getmarks();
d.display();
return 0;
}


input/output:-
Enter roll no:1241
Enter Name:netaji
Enter marks m1,m2,m3 
4 5 6

 roll no:1241
 Name: netaji
 Total marks=15

2.) multiple inheritance

Multiple inheritance occurs when a class inherits from more than one base class. So the class can inherit features from multiple base classes using multiple inheritance. This is an important feature of object oriented programming languages such as C++.
A diagram that demonstrates multiple inheritance is given below −

Example:
// cpp program to demonstrate multiple inheritance.


#include<iostream>
using namespace std;
class Emp
{
protected:

int eno;
float sal;

public:
void getdata()
{
cout<<"Enter employee no:";
cin>>eno;
cout<<"Enter emp. salary:";
cin>>sal;
}
};
class Dept
{
protected:
char dname[20];
char location[20];
public:
void setdata()
{
cout<<"Enter department name:";
cin>>dname;
cout<<"Enter location:";
cin>>location;
}
};
class  Details :public Emp, public Dept
{
int exp;
public:
void get()
{
getdata();
setdata();
cout<<"Enter experience:";
cin>>exp;
}
void show()
{
cout<<"eno="<<eno<<" "<<sal<<" "<<dname<<" "<<location<<" "<<exp;
}
};

int main()
{
Details d;
d.get();
d.show();
return 0;
}

input/output:-

Enter employee no:11
Enter emp. salary:10000
Enter department name:IT
Enter location:vizag
Enter experience:4

eno=11  10000  IT  vizag  4

3.)  Multilevel - Inheritance

*In this type of inheritance, a derived class is created from another derived class.
*If a class is derived from another derived class then it is called multilevel inheritance. So in C++ multilevel inheritance, a class has more than one parent class.

For example, if we take animals as a base class then mammals are the derived class which has features of animals and then humans are the also derived class that is derived from sub-class mammals which inherit all the features of mammals.


*A diagram that demonstrates multilevel inheritance is given below

// cpp program on multilevel inheritance.


#include<iostream>

using namespace std;

class student

{

         protected:

                   int roll_number;
          public:
                  void getnumber(int a)
                  {
                        roll_number=a;
                   }
                 void putnumber()
                 {
                        cout<<"roll number:"<<roll_number<<"\n";
                 }
};
class test :public student
{
         protected:
                     float sub1,sub2;
          public:
                    void getmarks(float x,float y)
                    {
                              sub1=x;
                              sub2=y;
                    }
                   void putmarks();
};
void test ::putmarks()
{
            cout<<"marks in sub1="<<sub1<<"\n";
            cout<<"marks in sub2="<<sub2<<"\n";
}
class result :public test
{
      float total;
      public:
           void display()
           {
                 total=sub1+sub2;
                 putnumber();
                 putmarks();
                 cout<<"total="<<total<<"\n";
            }
};
int main()
{

            result r;

            r.getnumber(1);
            r.getmarks(55,77);
            r.display();
            return 0;
}

output:-


roll number:1


marks in sub1=55


marks in sub2=77


total=132

4.)  Hierarchical - Inheritance 

Inheritance is the process of inheriting properties of objects of one class by objects of another class. The class which inherits the properties of another class is called Derived or Child or Sub class and the class whose properties are inherited is called Base or Parent or Super class. When more than one classes are derived from a single base class, such inheritance is known as Hierarchical Inheritance, where features that are common in lower level are included in parent class. Problems where hierarchy has to be maintained can be solved easily using this inheritance.
For example:-

 1.) Civil, Computer, Mechanical, Electrical are derived from Engineer.

 2.) Natural language, Programming language are derived from Language.

3.) Physics, Chemistry, Biology are derived from Science class.



Example of Hierarchical Inheritance in C++:-

// cpp program on hierarchical inheritance


#include<iostream>
using namespace std;
class A
{
 public:
  void show()
  {
      cout<<"show called..";
  }
};
class B: public A
{
 public:
  void display()
  {
   cout<<"display called..";
  }
};
class C: public A
{
 public:
  void output()
        {
          cout<<"output called..";
    } 
};
int main()
{
        B b;
       C c;
       b.display();
      b.show();
      c.output();
       c.show();
      return 0;
}

INPUT/OUTPUT:-

display called..show called..output called..show called..
5.) Hybrid - Inheritance  


What is Hybrid ?

The inheritance in which the derivation of a class involves more than one form of any inheritance is called hybrid inheritance. Basically C++ hybrid inheritance is   combination of two or more types of inheritance.
C++ Hybrid Inheritance Block Diagram

C++ Hybrid Inheritance Example

Here is a simple program to illustrate the concept of hybrid inheritance in C++.

// hybrid inheritance.cpp
#include <iostream>
using namespace std;
class A
{
  public:
  int x;
};
class B : public A
{
  public:
   B()      //constructor to initialize x in base class A
   {
     x = 10;
  }
};
class C
 {
       public:
                  int y;
              C()   //constructor to initialize y
              {
                   y = 4;
              }
};
class D : public B, public C   //D is derived from class B and class C
{
  public:
  void sum()
  {
      cout << "Sum= " << x + y;
  }
};

int main()
{
             D obj1;          //object of derived class D
            obj1.sum();
             return 0;
}                //end of program

Output

Sum= 14
Virtual base class in C++

-> An ambiguity can arise when several paths exist to a class from the same base class. This means that a child class could have duplicate sets of members inherited from a single base class.

-> C++ solves this issue by introducing a virtual base class. When a class is made virtual, necessary care is taken so that the duplication is avoided regardless of the number of paths that exist to the child class.


What is Virtual base class? Explain its uses.

-> When two or more objects are derived from a common base class, we can prevent multiple copies of the base class being present in an object derived from those objects by declaring the base class as virtual when it is being inherited. Such a base class is known as virtual base class. This can be achieved by preceding the base class’ name with the word virtual.

-> The virtual base class is used when a derived class has multiple copies of the base class.


// C++ program on multipath inheritance using virtual base class.

#include<iostream>
using namespace std;
class A
{
public:
void showA()
{
cout<<"showA"<<" ";
}
};
class B: public virtual A
{
public:
void showB()
{
cout<<"showB"<<" ";
}
};
class C: public virtual A
{
public:
void showC()
{
cout<<"showC"<<" ";
}
};

class D: public B, public C
{
public:
void showD()
{
cout<<"showD";
}
};
int main()
{
D d;
d.showA();
d.showB();
d.showC();
d.showD();
return 0;
}

OUTPUT:

showA  showB  showC  showD



No comments

NPTEL Programming in Java Jan 2024 Week 11

  Week 11 : Programming Assignment 1 Due on 2024-04-11, 23:59 IST The following code is missing some information needed to run the code. Add...