Search code examples
c++multiple-inheritanceopen-closed-principle

C++ How can I combine and add functionality to the same inherited method by a class with multiple inheritance?


So say I have the class empire. empire inherits populationContainer and landContainer as such:

class empire : public populationContainer, public landContainer

Both of those parent classes have the method update(), each of which do their own thing; for example, the pop container calculates pop growth and the land container calculates land expansion.

I currently cannot call empire.update() because it is ambiguous. How do I have both methods get called at once? Additionally, what if I also want empire to have more instructions under update()?

I can call each method in turn like such:

void empire::update() {
    populationContainer::update();
    landContainer::update();
    // Do other stuff
}

But doesn't this violate the open-closed principal? What if I want to add more 'container' classes with their own update() functions? I'd have to add each one to empire's update() function.


Solution

  • My solution would be:

    // If you add more base classes here, add them also to the 'update' method
    class empire : public populationContainer, public landContainer