Multiple Inheritance
A class can inherit more than one class. In such a case, all members of all
inherited classes will become members of the derived class.
Given the classes
ClassA and
ClassB, a class
ClassC can be defined as inheriting both:
class ClassA{};
class ClassB {};
class ClassC: public ClassA, public ClassB {};
In the program below, a class
Person is
declared, then a class
StateEmployee is
declared. Finally a third class called
Teacher,
derived both from
Person and
StateEmployee is declared.
All members of
Person and all members of
StateEmployee become members of
Teacher.
A
Teacher object will contain
name,
age,
setNameAge(),
printNameAge(), from
Person and
socialSecurityNr,
setSocialSEcurityNr(),
printSocialSEcurityNr(), from
StateEmployee.
Further, it will contain
subject,
setSubject() and
printSubject().
All members of
Teacher inherited from its base
classes will retain their visibility level,
as a result of the
Teacher declaration, in which
public comes before both of the inherited classes:
class Teacher: public Person, public StateEmployee
Example
#include <iostream>
#include <cstring>
using namespace std;
// Base class
class Person
{
string name;
int age;
public:
void setNameAge(string aName, int anAge)
{
name = aName;
age = anAge;
}
void printNameAge()
{
cout << "name: " << name << ", age: " << age << "\n";
}
};
// Base class
class StateEmployee
{
int socialSecurityNr;
public:
void setSocialSEcurityNr(int nr)
{
socialSecurityNr = nr;
}
void printSocialSEcurityNr()
{
cout << "SSN: " << socialSecurityNr << "\n";
}
};
// Teacher is derived from Person and StateEmployee
class Teacher : public Person, public StateEmployee
{
string subject;
public:
void setSubject(string aSubject)
{
subject = aSubject;
}
void printSubject()
{
cout << "subject is: " << subject << "\n";
}
};
int main()
{
Teacher teacher;
teacher.setSubject("Math");
teacher.setNameAge("Tony", 43);
teacher.setSocialSEcurityNr(1234);
teacher.setSubject("English");
teacher.printNameAge();
teacher.printSocialSEcurityNr();
teacher.printSubject();
}
Output
name: Tony, age: 43
SSN: 1234
subject is: English