saffronjam
saffronjam

Reputation: 59

Override a sub-class to a child-class

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

Answers (2)

anastaciu
anastaciu

Reputation: 23802

One way to solve it is to inherit Foo::Kid

Live sample

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

kabanus
kabanus

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

Related Questions