Multilevel Inheritence in C++
Multilevel Inheritance in C++ Programming
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 a class is derived from a class which is also derived from another class, i.e. a class having more than one parent classes, such inheritance is called Multilevel Inheritance. The level of inheritance can be extended to any number of level depending upon the relation. Multilevel inheritance is similar to relation between grandfather, father and child.For example,
- Student is derived from person and person is derived from class living things.
- Car is derived from vehicle and vehicle is derived from machine.
Syntax of Multilevel Inheritance
class base_classname
{
properties;
methods;
};
class intermediate_classname:visibility_mode base_classname
{
properties;
methods;
};
class child_classname:visibility_mode intermediate_classname
{
properties;
methods;
};
Example of Multilevel Inheritance in C++
C++ program to create a programmer derived from employee which is himself derived from person using Multilevel Inheritance.#include <iostream>
#include <conio.h>
using namespace std;
class person
{
char name[100],gender[10];
int age;
public:
void getdata()
{
cout<<"Name: ";
fflush(stdin); /*clears input stream*/
gets(name);
cout<<"Age: ";
cin>>age;
cout<<"Gender: ";
cin>>gender;
}
void display()
{
cout<<"Name: "<<name<<endl;
cout<<"Age: "<<age<<endl;
cout<<"Gender: "<<gender<<endl;
}
};
class employee: public person
{
char company[100];
float salary;
public:
void getdata()
{
person::getdata();
cout<<"Name of Company: ";
fflush(stdin);
gets(company);
cout<<"Salary: Rs.";
cin>>salary;
}
void display()
{
person::display();
cout<<"Name of Company: "<<company<<endl;
cout<<"Salary: Rs."<<salary<<endl;
}
};
class programmer: public employee
{
int number;
public:
void getdata()
{
employee::getdata();
cout<<"Number of programming language known: ";
cin>>number;
}
void display()
{
employee::display();
cout<<"Number of programming language known: "<<number;
}
};
int main()
{
programmer p;
cout<<"Enter data"<<endl;
p.getdata();
cout<<endl<<"Displaying data"<<endl;
p.display();
getch();
return 0;
}
Output
Enter data
Name: Karl Lens
Age: 31
Gender: Male
Name of Company: Dynamic Info
Salary: $21000
Number of programming language known: 4
Displaying data
Name: Karl Lens
Age: 31
Gender: Male
Name of Company: Dynamic Info
Salary: $21000
Number of programming language known: 4
Comments
Post a Comment