#include <iostream> using namespace std; // Base class class Person { public: void introduce() { cout << "I am a person." << endl; } }; // Derived class Student (virtual inheritance) class Student : virtual public Person { public: void study() { cout << "I am studying." << endl; } }; // Derived class Teacher (virtual inheritance) class Teacher : virtual public Person { public: void teach() { cout << "I am teaching." << endl; } }; // Derived class ResearchScholar (inherits from both Student and Teacher) class ResearchScholar : public Student, public Teacher { public: void research() { cout << "I am doing research." << endl; } }; int main() { ResearchScholar rs; rs.introduce(); // From Person (diamond problem solved by virtual inheritance) rs.study(); // From Student rs.teach(); // From Teacher rs.research(); // Own method return 0; }
Output
Short Explanation
-
Person is the base class.
-
Both Student and Teacher inherit from
Person
. -
ResearchScholar inherits from both
Student
andTeacher
. -
Without
virtual
inheritance,ResearchScholar
would get two copies ofPerson
, causing the diamond problem (ambiguity in callingintroduce()
). -
Using
virtual public Person
, only one shared copy ofPerson
exists, solving the issue.
Real-life analogy: A Research Scholar is both a Student and a Teacher, but still only one Person.
⮕ 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