2

Say you have the following class hierarchy:

class A
{
   public:
   virtual void foo() {}
}

class B
{
   public:
   virtual void foo() {}
}

class C: public A, public B
{
    public:
    virtual void foo() override {  } // This overrides both
}

class D: public A, public B
{
    public:
    // Is there syntax so that there is a separate override for each?
    // Maybe something like:
    // virtual void A::foo() override {}
    // virtual void B::foo() override {}
}

Is there a way to have two foo functions on class D, such that if D is passed as a reference to an A, one function in D is called, and if D is passed as a reference to a B a different function in D is called?

The use case would be if you are inheriting from two external libraries, and they just happen to have overlapping function specifiers?

curiousguy
  • 8,038
  • 2
  • 40
  • 58
bpeikes
  • 3,495
  • 9
  • 42
  • 80

1 Answers1

5

You can't exactly do that, but there's a workaround demonstrated by Stroustrup himself.

class A_foo_renamer : public A
{
    virtual void A_foo () = 0;
    virtual void foo() override { A_foo(); }
};

class B_foo_renamer : public B
{
    virtual void B_foo () = 0;
    virtual void foo() override { B_foo(); }
};

class D: public A_foo_renamer, public B_foo_renamer
{
   virtual void A_foo() override {}
   virtual void B_foo() override {}
   // leave A::foo and B::foo alone
};
n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
  • Is there any implementation overhead in this approach? – M.M Aug 09 '15 at 02:21
  • most compilers will compile A_foo_renamer to a single indirect jump (2-3 instructions on x64), though theoretically it's possible to just modify the vtable so that foo and A_too entries point to the same code. I don't know if any compiler does this. – n. m. could be an AI Aug 09 '15 at 04:37