Function Name Collision in Derived Class Inheritance
Consider the following code snippet:
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); } };
When compiling this code, the compiler generates the following error:
error: no matching function for call to 'C::foo(std::string&)' candidates are: int B::foo(int)
This error occurs because of function name shadowing. When the derived class B defines a function with the same name as a function in its base class A, the derived class function shadows the base class function.
Name Lookup Scope
Name lookup in a class scope follows these steps:
Solution
To resolve the function name collision, you can re-declare the base class function in the scope of the derived class. This ensures that both functions are visible within the derived class and its descendants:
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); } };
By adding using A::foo;, you specify that the foo function from the base class A is also available in the derived class B. Now, the code will compile without errors.
Additional Notes
"The following steps define the result of name lookup in a class scope, C. First, every declaration for the name in the class and in each of its base class sub-objects is considered. A member name f in one sub-object B hides a member name f in a sub-object A if A is a base class sub-object of B."
The above is the detailed content of How to Resolve Function Name Collision in C Derived Class Inheritance?. For more information, please follow other related articles on the PHP Chinese website!