C++: Private Inheritance

between the base and the derived class.

I am trying to privately derive the Executive class from both Employee and Money. In the Manager class, Money is used to store a wage, while in the Executive class, Money is used to store additional bonuses. However, I am getting a compiler warning that the direct base ‘Money’ is inaccessible in ‘Executive’ due to ambiguity.

I understand that private inheritance may be used as a form of composition or when the base’s interface should be hidden from outsiders. However, in this case, I cannot understand what kind of ambiguity the compiler is warning me about, since private inheritance does not allow outside classes or subclasses of a privately derived class to take advantage of the relation between the base and the derived class.

The compiler warning is indicating that there is an ambiguity in the use of the Money class in the Executive class. This is because you have privately derived the Executive class from both Employee and Money, and both the Manager class and the Executive class are using the Money class.

To resolve this ambiguity and avoid the warning, you can use a technique called virtual inheritance. Virtual inheritance allows a class to inherit from a base class such that only one instance of the base class is shared among all the derived classes.

To implement virtual inheritance, you need to make the inheritance of Money virtual in both the Manager and Executive classes. Here is the updated code:

class Money {
    // Money class code
};

class Employee {
    // Employee class code
};

class Manager : public virtual Employee, public virtual Money {
    // Manager class code
};

class Executive : public virtual Employee, public virtual Money {
    // Executive class code
};

By using virtual inheritance, you are ensuring that there is only one instance of Money shared between Manager and Executive classes. This resolves the ambiguity and eliminates the compiler warning.

Note: Virtual inheritance should be used carefully, as it can have performance implications and may require additional attention to object initialization.