Here’s a C++ program that shows how a Hierarchical Inheritance actually works with the help of Person,Teacher,and Student
If you found this post useful:
#include <iostream>
using namespace std;
// Base class
class Person {
public:
void walk() {
cout << "Walking..." << endl;
}
};
// Derived class 1
class Student : public Person {
public:
void study() {
cout << "Studying..." << endl;
}
};
// Derived class 2
class Teacher : public Person {
public:
void teach() {
cout << "Teaching..." << endl;
}
};
// Main function
int main() {
Student s1;
Teacher t1;
// Student object can use both Person and Student methods
s1.walk();
s1.study();
// Teacher object can use both Person and Teacher methods
t1.walk();
t1.teach();
return 0;
}
Output:
Walking...
Studying...
Walking...
Teaching...
Short Explanation:
-
Person→ Base class with methodwalk(). -
StudentandTeacher→ Both inherit fromPerson. -
Each child class adds its own unique method (
study()andteach()). -
In
main(),-
Studentobject uses both Person’s and Student’s methods. -
Teacherobject uses both Person’s and Teacher’s methods.
-
So, this is Hierarchical Inheritance in C++, where multiple child classes inherit from a single parent class.
Thanks for reading 💗!
⮕ Share it with others who might benefit.
⮕ Leave a comment with your thoughts or questions—I’d love to hear from you.
⮕ Follow/Subscribe to the blog for more helpful guides, tips, and insights.
Comments
Post a Comment