same function name different signature

Why the following code does not compile in g++?

1
2
3
4
5
6
7
8
9
10
struct A {
  int foo(int x) {
    return x * 2;
  }
};
struct B: A {
  int foo(int x, int y) {
    return foo(x) + y;
  }
};


Why function A::foo(int) is not available in function B::foo(int, int)?
If I change the function name from foo to bar in B, then it compiles fine.
Identifiers in "inner scope" do mask/hide names from "outer scope".
You do get same situation with:
1
2
3
4
5
6
7
int foo(int x, int y);

int main()
{
    int foo(int x);
    foo( 2, 4 ); // error: too many args to call, expected 1, have 2; did you mean '::foo'?
}


It should be possible to make A::foo explicitly visible in B.
1
2
3
4
5
6
7
8
9
10
11
struct A {
  int foo(int x) {
    return x * 2;
  }
};
struct B: A {
  using A::foo;
  int foo(int x, int y) {
    return foo(x) + y;
  }
};
This is indeed surprising the first time you see it. I think it is because the lookup rules are to first look for a matching name, and when it has found a matching name it starts to look at overloads in that scope without searching further.

In your case it finds a function named foo in B so it doesn't bother looking in A.
Last edited on
Can also specify to use foo() in A explicitly:

1
2
3
4
5
6
7
8
9
10
struct A {
	int foo(int x) {
		return x * 2;
	}
};
struct B : A {
	int foo(int x, int y) {
		return A::foo(x) + y;
	}
};

Topic archived. No new replies allowed.