Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get no matching function when I inherit this function [duplicate]

Possible Duplicate:
overloaded functions are hidden in derived class

I have Class A and Class B (subclass of A)

Class A has function

virtual void foo(int, int);
virtual void foo(int, int, int);

When I try to do

Class B with function

virtual void foo(int, int);

When I try to call foo(int, int, int) with the class the compiler won't let me because it says

no matching function for foo(int,int,int)
candidate is foo(int,int);
like image 771
DogDog Avatar asked Nov 24 '10 20:11

DogDog


3 Answers

The reason why has to do with the way C++ does name lookup and overload resolution. C++ will start at the expression type and lookup upwards until it finds a member matching the specified name. It will then only consider overloads of the member with that name in the discovered type. Hence in this scenario it only considers foo methods declared in B and hence fails to find the overload.

The easiest remedy is to add using A::foo into class B to force the compiler to consider those overloads as well.

class B : public A {
  using A::foo;
  virtual void foo(int, int);  
};
like image 88
JaredPar Avatar answered Nov 03 '22 15:11

JaredPar


The override in class B hides the methods of class A with the same name. (Do you have compiler warnings on? Most compilers warn about hidden virtual methods.)

To avoid this, add

using A::foo;

to class B (in whatever public/protected/private section is appropriate).

like image 41
aschepler Avatar answered Nov 03 '22 15:11

aschepler


Use

B b;
b.A::foo(1,2,3);

for example.

like image 1
Steve Townsend Avatar answered Nov 03 '22 14:11

Steve Townsend