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:

  1. Person Class: This is the base class for both Student and Teacher classes. It represents the common attributes and behaviors of a person, such as their name, age, and an introduce() method to introduce themselves.

  2. Student Class: The Student class inherits from the Person class using the public access specifier. This means that the Student class has access to all the public members of the Person class, including its attributes and methods. The Student class adds an additional attribute rollNumber and a displayInfo() method to display the student's information.

  3. Teacher Class: The Teacher class also inherits from the Person class using the public access specifier. The Teacher class adds an additional attribute subject and a displayInfo() method to display the teacher's information.

  4. main Function: In the main function, we create instances of the Student and Teacher classes and call their displayInfo() 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.