[ACCEPTED]-Function with same name but different signature in derived class-c++-faq
It is because name lookup stops if it finds 36 a name in one of your bases. It won't look 35 beyond in other bases. The function in B 34 shadows the function in A. You have to re-declare 33 the function of A in the scope of B, so 32 that both functions are visible from within 31 B and C:
class A
{
public:
void foo(string s){};
};
class B : public A
{
public:
int foo(int i){};
using A::foo;
};
class C : public B
{
public:
void bar()
{
string s;
foo(s);
}
};
Edit: The real description the Standard 30 gives is (from 10.2/2):
The following steps 29 define the result of name lookup in a class 28 scope, C. First, every declaration for the name 27 in the class and in each of its base class 26 sub-objects is considered. A member name 25 f in one sub- object B hides a member 24 name f in a sub-object A if A is a base 23 class sub-object of B. Any declarations that 22 are so hidden are eliminated from consideration. Each 21 of these declarations that was introduced 20 by a using-declaration is considered to 19 be from each sub-object of C that is of 18 the type containing the declara- tion 17 designated by the using-declaration.96) If 16 the resulting set of declarations are not 15 all from sub-objects of the same type, or 14 the set has a nonstatic member and includes 13 members from distinct sub-objects, there 12 is an ambiguity and the program is ill-formed. Otherwise 11 that set is the result of the lookup.
It 10 has the following to say in another place 9 (just above it):
For an id-expression [something like "foo"], name 8 lookup begins in the class scope of this; for 7 a qualified-id [something like "A::foo", A is a nested-name-specifier], name lookup begins in 6 the scope of the nested-name-specifier. Name 5 lookup takes place before access control 4 (3.4, clause 11).
([...] put by me). Note 3 that means that even if your foo in B is 2 private, the foo in A will still not be 1 found (because access control happens later).
Functions in derived classes which don't 15 override functions in base classes but which 14 have the same name will hide other functions 13 of the same name in the base class.
It is 12 generally considered bad practice to have 11 have functions in derived classes which 10 have the same name as functions in the bass 9 class which aren't intended to override 8 the base class functions as what you are 7 seeing is not usually desirable behaviour. It 6 is usually preferable to give different 5 functions different names.
If you need to 4 call the base function you will need to 3 scope the call by using A::foo(s)
. Note that this 2 would also disable any virtual function 1 mechanism for A::foo(string)
at the same time.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.