C++ Hierarchical Inheritance
Hierarchical inheritance inherits the property of one base class in more than one derived class.
C++ Hierarchical Inheritance Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
#include <iostream> using namespace std; class Person { char gender[10]; int age; public: void getPerson() { cout << "Age: "; cin >> age; cout << "Gender: "; cin >> gender; } void dispPerson() { cout << "Age: " << age << endl; cout << "Gender: " << gender << endl; } }; class Employee : public Person { float salary; public: void getEmployee() { Person::getPerson(); cout << "Salary: Rs."; cin >> salary; } void dispEmployee() { Person::dispPerson(); cout << "Salary: Rs." << salary << endl; } }; class Student : public Person { char level[20]; public: void getStudent() { Person::getPerson(); cout << "Class: "; cin >> level; } void dispStudent() { Person::dispPerson(); cout << "Level: " << level << endl; } }; int main() { Person per; Employee emp; Student stu; cout << "Student data" << endl; cout << "Enter data" << endl; stu.getStudent(); cout << endl << "Displaying data" << endl; stu.dispPerson(); cout << endl << "Staff Data" << endl; cout << "Enter data" << endl; emp.getEmployee(); cout << endl << "Displaying data" << endl; emp.dispPerson(); } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
Student data Enter data Age: 10 Gender: f Class: 5 Displaying data Age: 10 Gender: f Employee data Enter data Age: 30 Gender: m Salary: 25000 Display data Age: 30 Gender: m |