You can fix this using virtual inheritance.
Consider creating a common base class that defines only a pure virtual toString method (or, in fact, a pure virtual version of any methods that make sense for both IBase and Base2 ), for example
class Stringable { public: virtual string toString() = 0; };
Then inherit the Base2 class from IBase and Stringable :
class IBase : public Stringable { }; class Base2 : public Stringable { public: virtual string toString() { ... } };
Now this still won't work, because Class1 inherited two copies of the Stringable base class, only one of which has an implementation for toString in its inheritance hierarchy. This is called a scary diamond . However, if IBase and Base2 were to be inherited practically from Stringable , for example:
class IBase : virtual public Stringable { }; class Base2 : virtual public Stringable { public: virtual string toString() { ... } };
This then tells the compiler that there should only be one common base class Stringable , even if IBase and Base2 both inherited from the same class, which is exactly what you want, because then Base2::toString used for Class1 .
There is no “hidden error” in your second idea, but it’s somehow a pain in the butt to be implemented multiple times, as you probably understand.
Tyler mchenry
source share