What is multiple virtual inheritance?

class foo : public virtual bar, public virtual kung { // implementation of the method of the above inherited class }; 

the bar and kung class is an abstract class that contains a pure virtual method implemented inside foo clas ..

What is the use of this?

+4
source share
3 answers

In your case, it doesn’t matter if bars and kung are the most derived base classes until you use the methods in the bar and kung collision, but you would know about it if that happened, i.e. compiler errors in ambiguous definitions.

More about this in C ++ faq: http://www.parashift.com/c++-faq-lite/multiple-inheritance.html#faq-25.9

+1
source

If other future classes are obtained from foo more than one way, then the most derived class will contain only one virtual base class bar and kung :

 struct A : foo { }; struct B : foo { }; class Gizmo : public A, public B { }; // only *one* bar and kung base class. 

An object of type Gizmo has a unique base subobject of type bar and ditto for kung , and not two different for each derivation path.

Note that if a class has only pure virtual functions, and not non-static members and only base classes of the same nature, then there is no practical difference between virtual and non-virtual inheritance, since classes are empty. Other, smaller languages ​​call such classes “interfaces”, which means that they should be inherited from them, even if such languages ​​do not support multiple inheritance for common classes.

0
source

So the class is foo isa bar and isa kung.

If you have a function or method that accepts a bar object, an instance of the foo class will be created. Since the bar class has pure virtual methods, the compiler will need foo (or a class derived from foo) to determine the method if an object is created. The code that receives the bar object can then rely on the fact that the bar object passed to it implements this method, even if the object is an instance of the foo class (or the class derived from foo).

Similarly for the kung class.

So, if the foo class implements all pure virtual methods in the kung bar (which the compiler will require to instantiate the foo object), then the foo object can be passed to anything that requires a bar, kung or foo.

0
source

Source: https://habr.com/ru/post/1411374/


All Articles