C++ A multiple inheritance pproblem with pure virtual functions

前端 未结 1 1593
南旧
南旧 2021-01-25 02:27

I have produced a minimal example to replicate the problem I am seeing with a more complex class hierarchy structure:

#include 
#include 

        
1条回答
  •  北海茫月
    2021-01-25 02:43

    Currently your F is derived from C in two different ways. This means that an F object has two separate C bases, and so there are two instances of C::Print().

    You only override the one coming via E currently.

    To solve this you must take one of the following options:

    • Also override the one coming via D, either by implementing D::Print() or F::Print()
    • Make Print non-pure
    • Use virtual inheritance so that there is only a single C base.

    For the latter option, the syntax adjustments would be:

    class E : virtual public C
    

    and

    class D : public B, public BB, virtual public C
    

    This means that D and E will both have the same C instance as their parent, and so the override E::Print() overrides the function for all classes 'downstream' of that C.

    For more information , look up "diamond inheritance problem". See also Multiple inheritance FAQ

    0 讨论(0)
提交回复
热议问题