C++ method only visible when object cast to base class?

You have shadowed a method. For example:

struct base
{
    void method(int);
    void method(float);
};

struct derived : base
{
    void method(int);
    // base::method(int) is not visible.
    // base::method(float) is not visible.
};

You can fix this with a using directive:

class derived : public base
{
    using base::method; // bring all of them in.

    void method(int);
    // base::method(int) is not visible.
    // base::method(float) is visible.
};

Since you seem insistent about the number of parameters, I’ll address that. That doesn’t change anything. Observe:

struct base
{
    void method(int){}
};

struct derived : base
{
    void method(int,int){}
    // method(int) is not visible.
};

struct derived_fixed : base
{
    using base::method;
    void method(int,int){}
};

int main(void)
{
    {
        derived d;

        d.method(1, 2); // will compile
        d.method(3); // will NOT compile
    }
    {
        derived_fixed d;

        d.method(1, 2); // will compile
        d.method(3); // will compile
    }
}

It will still be shadowed regardless of parameters or return types; it’s simply the name that shadows. using base::<x>; will bring all of base‘s “<x>” methods into visibility.

Leave a Comment