-2

This does not compile:

struct Base
{
    void something( int a ) { }
};
struct Derived : public Base
{
    static void something()
    {
        std::unique_ptr<Derived> pointer = std::make_unique<Derived>();
        pointer->something( 11 );
    }
};

It’s possible to fix with using Base::something but still, is it possible to make inheritance work as advertised even inside methods?

Soonts
  • 20,079
  • 9
  • 57
  • 130

2 Answers2

2

By using the same name for the function in the derived class you hide the symbol from the base class.

You can solve it by pulling in the name from the base class with the using statement:

struct Derived : public Base
{
    // Also use the symbol something from the Base class
    using Base::something;

    static void something()
    {
        std::unique_ptr<Derived> pointer = std::make_unique<Derived>();
        pointer->something( 11 );
    }
};
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

I'm not exactly sure what you are trying to accomplish. I added virtual, and changed the name of the Derived something class function, and put in two variants. One variant calls through virtual inheritance, the other calls Base class member function directly.

#include <iostream>

using std::cout;

namespace {

struct Base {
    virtual ~Base();
    virtual void something(int a) { std::cout << "Base a:" << a << "\n"; }
};

Base::~Base() = default;

struct Derived : Base {
    void something(int b) override { std::cout << "Derived b:" << b << "\n"; }
    static void action() {
        std::unique_ptr<Derived> pointer = std::make_unique<Derived>();
        pointer->something(11);
    }
    static void other_action() {
        std::unique_ptr<Derived> pointer = std::make_unique<Derived>();
        pointer->Base::something(11);
    }
};

} // anon

int main() {
    Derived::action();
    Derived::other_action();
}
Eljay
  • 4,648
  • 3
  • 16
  • 27