Reputation: 59
How does one go about overriding such a function in the example below?
It's clearly not working the way I wrote it, but is it possible to implement something similar?
class Foo
{
public:
class Kid
{
public:
virtual void DoSomething();
};
};
class FirstBar : public Foo
{
public:
void Foo::Kid::DoSomething() override;
};
class SecondBar : public Foo
{
public:
void Foo::Kid::DoSomething() override;
};
Upvotes: 1
Views: 55
Reputation: 23802
One way to solve it is to inherit Foo::Kid
class FirstBar : public Foo::Kid
You can inherit both Foo
and Foo::Kid
if you need to:
class FirstBar : public Foo::Kid, public Foo
Upvotes: 1
Reputation: 25895
My take on it - your bars want to have Kids
of their own, properly inheriting:
#include<iostream>
class Foo
{
public:
class Kid
{
public:
virtual void DoSomething() {std::cout<<"Kid!\n";}
};
};
class FirstBar : public Foo
{
public:
class Kid : Foo::Kid {
public:
void DoSomething() override {std::cout<<"Kid Bar 1!\n";}
};
};
class SecondBar : public Foo
{
public:
class Kid : Foo::Kid {
public:
void DoSomething() override {std::cout<<"Kid Bar 2!\n";}
};
};
int main() {
Foo::Kid().DoSomething();
FirstBar::Kid().DoSomething();
SecondBar::Kid().DoSomething();
return 0;
}
Note inheriting from Foo
is unnecessary unless Kid
is defined as protected
, but I left the inheritance in case it makes sense for other reasons.
Upvotes: 2