Home > Backend Development > C++ > How to Resolve Function Name Collision in C Derived Class Inheritance?

How to Resolve Function Name Collision in C Derived Class Inheritance?

Patricia Arquette
Release: 2024-12-30 13:40:16
Original
623 people have browsed it

How to Resolve Function Name Collision in C   Derived Class Inheritance?

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); } };
Copy after login

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)
Copy after login

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:

  1. Consider all declarations for the name in the class and its base classes.
  2. Eliminate any declarations hidden by other declarations in base classes.

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); } };
Copy after login

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 Standard defines name lookup in class scope as follows:
"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."
  • Name lookup occurs before access control. Therefore, even if the foo function in B is private, the foo function in A will still not be found.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template