It is not possible to find the function of the base word if the base class has two functions with the same name

I have a base class that has two functions with the same name, but with different signatures in two-level inheritance.

struct A { virtual void f(int) { } virtual void f(int, int) { }; virtual void f1(int) { } }; struct B: public A { }; struct C: public B { void f(int, int) { } void f1(int) { } }; int main() { C obj; obj.f1(0); obj.f(0,0); obj.f(0); // (1) cannot be found obj.B::f(0); // (2) works } 

I would expect my compiler (gcc-4.3.2) to find the correct definition in (1) , but I get

 g++ main.cpp -o main main.cpp: In function 'int main()': main.cpp:20: error: no matching function for call to 'C::f(int)' main.cpp:10: note: candidates are: virtual void C::f(int, int) distcc[2200] ERROR: compile main.cpp on localhost failed make: *** [main] Error 1 

(2) on the other hand works.

What do I need to fix to do the job (1) in general?

+6
c ++ inheritance
source share
3 answers

Write using A::f inside the definition of C.

You are a victim of hiding the name! void C::f(int, int) hides void A::f(int) just because.

+6
source share

C ++ name lookup rules have this so that if a name is redefined in one scope, all overloads of that name are hidden.

But you can use using to help. Like this:

 class A { public: int f(int x) { cout << "A::f 1\n"; } int f(int x, int y) { cout << "A::f 2\n"; } }; class B : public A { public: using A::f; int f(int x) { cout << "B::f 1\n"; } }; int main() { B b; bf(27, 34); return 0; } 

Exit:

 A::f 2 
+4
source share

The short answer to the question "why" is "because it works." You hide the overload of f(int) in C. The longer answer is much longer.

You can hide it by doing the following:

 struct C: public B { using A::f; void f(int, int) { } void f1(int) { } }; 
+3
source share

All Articles