C ++ multiple inheritance question

The script creating this is quite complicated, so I cross out a few fragments and give an accurate idea of ​​the corresponding classes.

/* This is inherited using SI by many classes, as normal */ class IBase { virtual string toString()=0; }; /* Base2 can't inherit IBase due to other methods on IBase which aren't appropriate */ class Base2 { string toString() { ... } }; /* a special class, is this valid? */ class Class1 : public IBase, public Base2 { }; 

So is this really? Will there be conflicts on toString? Or can Class1 use Base2 :: toString to satisfy IBase? As I said, there are many other things that are not shown, so suggestions for major design changes in this example are probably not that useful ... although any general suggestions / tips are welcome.

My other thought was something like this:

 class Class1 : public IBase, public Base2 { virtual string toString() { return Base2::toString(); } }; 

These are assemblies and links, but I have no idea if it has hidden errors.

+6
c ++ multiple-inheritance
source share
2 answers

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.

+2
source share

This should work fine.

You properly redefine the IBase interface to provide a definition of ToString() , which will be set to Base2::ToString() .

Note that Base2 does not declare toString () as virtual, so Class1 cannot override the behavior of Base2::ToString . There is no ambiguity.

And, besides, this is not a classical diamond problem in multiple inheritance, solved virtual inheritance , since they do not share the base class.

+1
source share

All Articles