Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Derived class overriding base class functions again

Tags:

c++

In this thread the author of the accepted answer explains why the overridden method in the derived class can not be resolved by the compiler. However the example is relative to a type cast resolution, that is both the base and derived overloaded method have one parameter only and the ambiguity is limited to that parameter type.

But where is the ambiguity when the overloaded methods have a different number of parameters, like in this example?

Note that I'm not asking why the example produces a compile error, I'm asking why the language was designed this way.

#include <iostream>
using namespace std;

class A
{
public:
   inline int f(int x) { return x; }
};

class B: public A
{
public:
   inline int f(int x, int y) { return x+y; }
};


int main()
{
  B b;

  cout << b.f(1) << endl; // COMPILE ERROR
  cout << b.f(1,2) << endl;
}
like image 505
Robert Kubrick Avatar asked Nov 01 '22 23:11

Robert Kubrick


1 Answers

The reason you get a compiler error is that f from class A is hidden by the f in class B.

When the compiler does member name lookup, it uses base classes only if the name is not found in the object's class, so it doesn't matter if you have a member in a base class that has a proper parameter list for your call.

From the standard:

10.2.5 Otherwise (i.e., C does not contain a declaration of f or the resulting declaration set is empty), S(f, C) is initially empty. If C has base classes, calculate the lookup set for f in each direct base class subobject Bi , and merge each such lookup set S(f, Bi) in turn into S(f, C).

like image 133
imreal Avatar answered Nov 10 '22 01:11

imreal