C++ inheritance overloads functions with different parameters

814 views Asked by At

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;
}
1

There are 1 answers

0
Vlad from Moscow On BEST ANSWER

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