Reputation: 3685
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
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