Multiple Inheritance, C++ and Same Method Signature in Multiple Super Classes

Sam picture Sam · Jul 20, 2011 · Viewed 13.7k times · Source

I have no experience in C++, and I come from a Java background. Lately, I was asked in an interview on why Java would not allow multiple inheritence and the answer was pretty easy. However, I am still curious on how C++ deals with that since it allows you to inherit from more than one class.

Specifically, say there is a class called MechanicalEngineer and another called ElectricalEngineer. Both have a method called buildRobot().

What happens if we make a third class RoboticsEngineer, that inherets from both and does not override that method, and you just call:

(some instance of RoboticsEngineer).buildRobot()

Will an exception be thrown, or the method from one of the super-classes will be used? If so, how does the compiler know which class to use?

Answer

sergio picture sergio · Jul 20, 2011

The compiler will flag this kind of situation (i.e., attempting to call (some instance of RoboticsEngineer).buildRobot()) as an error.

This happens because the derived object has got a copy of both base objects (a MechanicalEngineer instance and an ElectricalEngineer instance) inside of itself and the method signature alone is not enough to tell which one to use.

If you override buildRobot in your RoboticsEngineer, you will be able to say explicitly which inherited method to use by prefixing the class name, e.g.:

void RoboticsEngineer::buildRobot() {
    ElectricalEngineer::buildRobot()
}

By the same coin, you can actually "force" the compiler to use one version or another of buildRobot by prefixing it with the class name:

 (some instance of RoboticsEngineer).ElectricalEngineer::buildRobot();

in this case the ElectricalEngineer implementation of the method will be called, no ambiguity.

A special case is given when you have an Engineer base class to both MechanicalEngineer and ElectricalEngineer and you specify the inheritance to be virtual in both cases. When virtual is used, the derived object does not contain two instances of Engineer, but the compiler makes sure that there is only one of it. This would look like this:

 class Engineer {
      void buildRobot();
 };

 class MechanicalEngineer: public virtual Engineer {

 };

 class ElectricalEngineer: public virtual Engineer {

 };

In this case,

(some instance of RoboticsEngineer).buildRobot();

will be resolved without ambiguities. The same is true if buildRobot is declared virtual and overridden in one of the two derived classes. Anyway, if both derived classes (ElectricalEngineer and MechanicalEngineer) overrides buildRobot, then ambiguity arises once again and the compiler will flag the attempt at calling (some instance of RoboticsEngineer).buildRobot(); as an error.