3

How is this even allowed to compile and run?

Since BaseA and BaseB have pure virtual functions, each should be overridden in Derived in order to be able to instantiate the class. Does this mean that the foo() override implements both?

Is there any way to implement each virtual function differently and call them explicitly?

struct BaseA  { virtual void foo() = 0; };
struct BaseB  { virtual void foo() = 0; };


struct Derived : public BaseA, public BaseB
{
    void foo() override {}
};


int main()
{
    Derived a;
    a.foo();
    return 0;
}
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
galinette
  • 8,896
  • 2
  • 36
  • 87
  • 5
    Yes, the one implementation has the correct signature to implement `void foo()` for either parent class. The easy way to have different implementations is to rename one to a different name; the harder way it so create an interstitial shim concrete class from both BaseA and BaseB that has different implementations, and then have Derived be derived from that MidA and MidB; users of Derived will have to specify if they want the MidA::foo() or the MidB::foo(). (Credit to Bjarne Stroustrup for the interstitial implementation class idea.) – Eljay Apr 24 '23 at 14:59

0 Answers0