1

I have a small base class that defines 3 overloads for a function. Overload A calls overload B which is pure virtual, and its implementation in the derived class calls overload C.

My complete code is as follows:

struct Base {
        int func(int a) {return func(a, a+1);}
        int func(int a, int b, int c) {return a+b+c;}
        virtual int func(int a, int b)=0;
};

struct Derived : public Base {
        int func(int a, int b);
};

int Derived::func(int a, int b) {
        return func(a,b,a+b);
}

int main(int argc, char* argv[]) {
        Derived d;
        d.func(1);
        return 0;
}

This code yields the errors:

test.cpp: In member function ‘virtual int Derived::func(int, int)’:
test.cpp:12:21: error: no matching function for call to ‘Derived::func(int&, int&, int)’
   12 |  return func(a,b,a+b);
      |                     ^
test.cpp:11:5: note: candidate: ‘virtual int Derived::func(int, int)’
   11 | int Derived::func(int a, int b) {
      |     ^~~~~~~
test.cpp:11:5: note:   candidate expects 2 arguments, 3 provided
test.cpp: In function ‘int main(int, char**)’:
test.cpp:17:10: error: no matching function for call to ‘Derived::func(int)’
   17 |  d.func(1);
      |          ^
test.cpp:11:5: note: candidate: ‘virtual int Derived::func(int, int)’
   11 | int Derived::func(int a, int b) {
      |     ^~~~~~~
test.cpp:11:5: note:   candidate expects 2 arguments, 1 provided

Why does the compiler fail to find the correct overload twice? (once in the call to overload C in the derived class, and once when calling overload A in the main)

Tomer
  • 632
  • 3
  • 14

1 Answers1

2

If you declare a function in a derived class with the same name as in the base class, the declaration in the derived class will shadow the functions in the base class.

So in Derived, the only visible func is the (int, int) one.

One easy way to solve this is to pull the base class functions into the overload set with using.

struct Derived : public Base {
        using Base::func; // All the func overloads are now pulled into Derived's scope
        int func(int a, int b);
};
super
  • 12,335
  • 2
  • 19
  • 29