Write a C++ program for multiple inheritance.
Q.) Write a C++ program for multiple inheritance.
Subject: Object Oriented Programming Methodology#include
using namespace std;
class Person {
public:
string name;
int age;
Person(string name, int age) {
this->name = name;
this->age = age;
}
void introduce() {
cout << "Hello, my name is " << name << " and I am " << age << " years old." << endl;
}
};
class Student : public Person {
public:
int rollNumber;
Student(string name, int age, int rollNumber) : Person(name, age) {
this->rollNumber = rollNumber;
}
void displayInfo() {
introduce();
cout << "My roll number is " << rollNumber << endl;
}
};
class Teacher : public Person {
public:
string subject;
Teacher(string name, int age, string subject) : Person(name, age) {
this->subject = subject;
}
void displayInfo() {
introduce();
cout << "I teach " << subject << endl;
}
};
int main() {
Student student("John Doe", 20, 12345);
student.displayInfo();
cout << endl;
Teacher teacher("Jane Smith", 30, "Mathematics");
teacher.displayInfo();
return 0;
}
Explanation:
Person Class: This is the base class for both
Student
andTeacher
classes. It represents the common attributes and behaviors of a person, such as their name, age, and anintroduce()
method to introduce themselves.Student Class: The
Student
class inherits from thePerson
class using thepublic
access specifier. This means that theStudent
class has access to all the public members of thePerson
class, including its attributes and methods. TheStudent
class adds an additional attributerollNumber
and adisplayInfo()
method to display the student's information.Teacher Class: The
Teacher
class also inherits from thePerson
class using thepublic
access specifier. TheTeacher
class adds an additional attributesubject
and adisplayInfo()
method to display the teacher's information.main Function: In the
main
function, we create instances of theStudent
andTeacher
classes and call theirdisplayInfo()
methods to display their information.
The program demonstrates the concept of multiple inheritance in C++, where a class can inherit from more than one parent class. In this case, both Student
and Teacher
classes inherit from the Person
class, allowing them to access and use the attributes and methods of the Person
class.