Home >Backend Development >C++ >Why Does 'Function with Same Name but Different Signature in Derived Class Not Found' Occur in C Inheritance?

Why Does 'Function with Same Name but Different Signature in Derived Class Not Found' Occur in C Inheritance?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-21 03:40:09787browse

Why Does

Function Hiding in Class Hierarchies: Understanding "Function with Same Name but Different Signature in Derived Class Not Found" Error

In object-oriented programming, derived classes can inherit members from their base classes. However, issues may arise when functions with the same name but differing signatures exist in both the base and derived classes. This can lead to errors such as "Function with same name but different signature in derived class not found."

To illustrate this problem, 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); // Error: no matching function
    }
};

When compiling this code, the compiler encounters an error in the foo(s) call within the bar() function of class C. Despite the foo(string s) function being present in the base class A, the compiler fails to recognize it due to a phenomenon known as function hiding.

In this scenario, the foo(int i) function defined in class B hides the foo(string s) function inherited from class A. This is because name lookup in class hierarchies stops at the first declaration of a matching name. Thus, when the lookup process reaches class B, it finds the foo(int i) function and disregards the overridden foo(string s) function in the base class.

To resolve this issue, one must explicitly redeclare the base class function in the scope of the derived class. By using the using keyword to inherit the base class function, both functions become visible within the derived class and its subclasses:

class A {
public:
    void foo(string s) {}
};

class B : public A {
public:
    int foo(int i) {}
    using A::foo; // Redeclare base class foo function
};

class C : public B {
public:
    void bar() {
        string s;
        foo(s); // Now finds the base class foo(string s)
    }
};

By incorporating this line in class B, name lookup will correctly consider both the foo(int i) and foo(string s) functions, resolving the function hiding issue.

The above is the detailed content of Why Does 'Function with Same Name but Different Signature in Derived Class Not Found' Occur in C Inheritance?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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