Multiple Inherited Functions with Same Signature Not Overloaded
In object-oriented programming, inheritance allows classes to inherit properties and methods from parent classes. However, a common issue arises when multiple inherited classes have functions with the same name but different signatures.
Problem
Consider the following code snippet:
#include <iostream> struct Base1 { void foo(int); }; struct Base2 { void foo(float); }; struct Derived : public Base1, public Base2 { }; int main() { Derived d; d.foo(5); // Ambiguous call to "foo" std::cin.get(); return 0; }
This code produces an "ambiguous call to foo" error, indicating that the call to foo cannot be resolved because there are multiple inherited functions with the same name but different signatures.
Explanation
According to C member lookup rules, when a class inherits from multiple base classes and there are multiple declarations for the same name, any hidden declarations are eliminated. If the resulting set of declarations is from different types or includes nonstatic members from distinct base classes, an ambiguity occurs.
In the example above, both Base1 and Base2 define a foo function, but they have different signatures. When Derived inherits from Base1 and Base2, there are two distinct declarations for foo with different types. This results in ambiguity, causing the compilation error.
Solution
To resolve the ambiguity, you can use using declarations to specify which base class's version of foo to use. For instance:
class Derived : public Base1, public Base2 { using Base1::foo; };
This using declaration ensures that the foo function from Base1 is used in Derived.
Gotcha
Note that in the second code snippet you provided, the Derived class has only one foo function (with a float parameter). This is because the foo function from Base1 is hidden by the foo function from Derived. Therefore, d.foo(5) calls the foo function with a float parameter from Derived, not Base1.
So, to answer the question in the title, multiple inherited functions with the same name but different signatures are not treated as overloaded functions because it would result in ambiguity. Instead, the compiler requires explicit resolution using using declarations or other techniques to specify which function should be used.
The above is the detailed content of How Do Multiple Inherited Functions with Identical Names but Different Signatures Resolve in C ?. For more information, please follow other related articles on the PHP Chinese website!