C++ Multiple Inheritance
Multiple inheritance is when a single class inherits from more than one base class at the same time. This lets a class combine features from several sources, gathering members from each parent into one object.
Inheriting from more than one class
To inherit from several base classes, list them after the colon separated by commas, each with its own access mode. The derived class then receives the accessible members of every base class you named.
Combining two base classes
#include <iostream>
using namespace std;
class Engine {
public:
void start() { cout << "Engine started\n"; }
};
class Radio {
public:
void playMusic() { cout << "Playing music\n"; }
};
// Car inherits from BOTH Engine and Radio
class Car : public Engine, public Radio {
public:
void drive() { cout << "Driving\n"; }
};
int main() {
Car myCar;
myCar.start(); // from Engine
myCar.playMusic(); // from Radio
myCar.drive(); // from Car
return 0;
}Here Car pulls start() from Engine and playMusic() from Radio, then adds drive() of its own. One object now has the combined abilities of both parents.
- Separate each base class with a comma in the class header.
- Give each base class its own access mode, usually public.
- The derived object can use accessible members from all parents.
Handling a name that exists in both parents
#include <iostream>
using namespace std;
class Printer {
public:
void turnOn() { cout << "Printer on\n"; }
};
class Scanner {
public:
void turnOn() { cout << "Scanner on\n"; }
};
class AllInOne : public Printer, public Scanner {
};
int main() {
AllInOne device;
device.Printer::turnOn(); // say which parent you mean
device.Scanner::turnOn();
return 0;
}Multiple inheritance is powerful but can get tangled quickly, so reach for it only when a class truly needs to combine unrelated features. When parents share member names, always resolve the ambiguity clearly.