13. CPP-Hierarchical Inheritance

CPP Multiple Inheritance: Previous                                              Next: CPP Important Points

This type of inheritance is just opposite to multiple inheritance. Hierarchical inheritance makes a tree relationship in which base class can have one or more derived class.


Structure is :
#include
#define SIZE 25;
class Person
{
private:
char name[SIZE];
long contact;
Person()
{
cout<<”enter name = “;
cin.getLine(name,SIZE);
cout<<”enter your contact number = “;
cin>>contact;
}
void display()
{
cout<<”name is = “<
cout<<”contact number is =”<
}
};
class Student : protected Person
{
private:
int marks[3];
int rollno,sum=0;
float per;
Student()
{
cout<<”Enter roll number = “;
cin>>rollno;
for(inti=0;i<3 i="" span="">
{
cout<<”Enter marks =”;
cin>>marks[i];
sum=sum+marks[i];
}
}
void display()
{
Person ::display();
cout<<”rollnumber is =”<
cout<<”total marks of student is = “<
per=sum/3;
cout<<”percentage is = “ <
}
};
class employee : protected person
{
private:
float salary;
intdeptno;
float bonus = 0;
employee( )
{
cout<<“Enter Salary : ”;
cin>>salary;
cout<<“Enter Dept No. : ”;
cin>>deptno;
cout<<“Enter Bonus : ”;
cin>>bonus;
}
void display( )
{
person::display( );
cout<<“Salary is : ”<
cout<<“Dept No. is : ”<
salary = salary + bonus
cout<<“Salary after Bonus is : ”<
}
};
void main( )
{
student std;
std.display( );
employee emp;
emp.display( );
}
Output:


CPP Multiple Inheritance: Previous                                              Next: CPP Important Points