1

I am working on a project which uses class inheritance and requires lots of overloads in both the base and derived class, I have simplified the code, but I wouldn't want to unnecessarily copy and paste since that's supposed to be what inheritance is for.

#include <iostream>

class Base
{
public:
    Base() = default;

    //base const char* overload
    void foo(const char* message)
    {
        std::cout << message << std::endl;
    }
    //other overloads ...
};
class Derived : public Base
{
public:
    Derived() = default;

    //derived int overload
    void foo(int number)
    {
        std::cout << number << std::endl;
    }
};

int main()
{
    Derived b;
    b.foo(10); //derived overload works
    b.foo("hi"); //causes error, acts as if not being inherited from Base class
    return 0;
}
2
  • 1
    Add using Base::foo; in the body of Derived. Otherwise, only Derived::foo overloads are visible. The issue is not overload resolution, it's name lookup. Commented Apr 11, 2020 at 22:56
  • Common question - not the clearest distillation of Q or A, but for example: stackoverflow.com/a/16837660/410767 / "why" version of this question: stackoverflow.com/q/1628768/410767 Commented Apr 11, 2020 at 22:57

1 Answer 1

0

You can use the using declaration in the derived class like

using Base::foo;

to make visible in the derived class the overloaded function(s) foo declared in the base class.

Here is your program within which the using declaration is inserted.

#include <iostream>

class Base
{
public:
    Base() = default;

    //base const char* overload
    void foo(const char* message)
    {
        std::cout << message << std::endl;
    }
    //other overloads ...
};
class Derived : public Base
{
public:
    Derived() = default;

    using Base::foo;
    //derived int overload
    void foo(int number)
    {
        std::cout << number << std::endl;
    }
};

int main()
{
    Derived b;
    b.foo(10); //derived overload works
    b.foo("hi"); //causes error, acts as if not being inherited from Base class
    return 0;
}

The program output is

10
hi
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.