What is Multiple Inheritance?
Multiple Inheritance is the process of deriving a class from more than one base class. An important point to be noted is protected data members. Protected data members are accessible only by the class in which they are declared and the class immediately derived from it, while further inheritance is determined by the visibility mode. This helps in data hiding while maintaining the functionality of the classes. For example, say class ‘C’ is derived from base classes ‘A’ and ‘B’. This is an example of multiple inheritances. If all data members of classes ‘A’ and ‘B’ are public, they are all accessible by each other, as well as class ‘C’ directly. If data members are private, they can be accessed by ‘C’ only if specifically defined in ‘A’ or ‘B’. If data members are protected in ‘B’, they can be accessed only by ‘B’ and directly derived class ‘C’.
Availability of data members after the immediately derived class depends on the inheritance mode, public or private. In another example, class ‘R’ is derived from class ‘Q’, which was further derived from class ‘P’. Here, ‘P’ is the base class for ‘Q’, and ‘Q’ is the base class for ‘R’. This is an example of multi-level inheritance. Now if we consider class ‘P’ having protected members derived in public visibility mode to class ‘Q’, these members shall become protected members of class ‘Q’, and will again become available to class ‘R’. However, if the members of ‘P’ are derived to ‘Q’ in private mode, they shall become private members of ‘Q’, and shall not be available to ‘R’. Hence, protected data members can be used in minimum two classes, the one in which they are declared, and the one immediately derived from it.
Multiple Inheritance Sample Program:
class stu //Base Class//
public: //If not declared, data members are by default defined as private//
cout << “Enter stuid, name”;
cin >> id >> name;
cout << “ID=” << id << endl;
cout << “Name=” << name << endl;
class marks //Base class
protected: //without this command, data members will not be available next//
int m1, m2, m3; // without ‘protected:’ command, m1, m2, & m3 are private members//
cout << “Enter 3 subject marks:”;
cin >> m1 >> m2 >> m3;
cout << “M1=” << m1 << endl;
cout << “M2=” << m2 << endl;
cout << “M3=” << m3 << endl;
class result : public stu, public marks; //Derived Class//
cout << “Total=” << tot << endl;
cout << “Average=” << avg << endl;
result r //Object