I have a function with the same name, but with different signature in a base and derived classes. When I am trying to use the base class’s function in another class that inherits from the derived, I receive an error. See the following code:
class A { public: void foo(string s){}; }; class B : public A { public: int foo(int i){}; }; class C : public B { public: void bar() { string s; foo(s); } };
I receive the following error from the gcc compiler:
In member function `void C::bar()': no matching function for call to `C::foo(std::string&)' candidates are: int B::foo(int)
If I remove int foo(int i){}; from class B, or if I rename it from foo1, everything works fine.
What’s the problem with this?
Functions in derived classes which don’t override functions in base classes but which have the same name will hide other functions of the same name in the base class.
It is generally considered bad practice to have have functions in derived classes which have the same name as functions in the bass class which aren’t intended to override the base class functions as what you are seeing is not usually desirable behaviour. It is usually preferable to give different functions different names.
If you need to call the base function you will need to scope the call by using
A::foo(s). Note that this would also disable any virtual function mechanism forA::foo(string)at the same time.