bpeikes
bpeikes

Reputation: 3685

Is it possible to override the virtual function of a specific parent?

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?

Upvotes: 2

Views: 95

Answers (1)

n. m. could be an AI
n. m. could be an AI

Reputation: 119847

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
};

Upvotes: 5

Related Questions