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;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
MaximV
  • 155
  • 11
  • 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. – Igor Tandetnik Apr 11 '20 at 22:56
  • Common question - not the clearest distillation of Q or A, but for example: https://stackoverflow.com/a/16837660/410767 / "why" version of this question: https://stackoverflow.com/q/1628768/410767 – Tony Delroy Apr 11 '20 at 22:57

1 Answers1

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
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335