Multiple Inherited Functions with Same Name: Why Not Overloaded?
In C , when multiple classes inherit functions with the same name but different signatures, the compiler treats these functions as distinct members rather than overloaded functions. This leads to ambiguity when calling the functions from a derived class.
Consider the following example:
struct Base1 { void foo(int); }; struct Base2 { void foo(float); }; struct Derived : public Base1, public Base2 { };
Here, both Base1 and Base2 define a function named foo with different parameters. When calling d.foo(5) from the derived class Derived, the compiler raises an "ambiguous call" error.
Unlike overriding, which requires the function signatures to be identical, overloading allows functions with the same name but different parameters. However, this rule does not apply to multiple inherited functions.
According to C member lookup rules, when multiple declarations of the same member name exist in a derived class, the declarations from different base classes are considered ambiguous. This occurs when either the declarations are not all from sub-objects of the same type or when there is a nonstatic member from distinct sub-objects.
To resolve this ambiguity, you can use the using declaration to explicitly specify which base class's function should be called:
struct Derived : public Base1, public Base2 { using Base1::foo; using Base2::foo; }; int main() { Derived d; d.foo(5); // Calls Base1::foo(int) d.foo(5.0f); // Calls Base2::foo(float) }
In the second code snippet you provided:
struct Base { void foo(int); }; struct Derived : public Base { void foo(float); };
The function foo(float) in Derived overrides the foo(int) function in the base class. Therefore, when calling d.foo(5), the foo(float) function is invoked correctly without any ambiguity.
The above is the detailed content of Why Don't Multiple Inherited Functions with the Same Name Overload in C ?. For more information, please follow other related articles on the PHP Chinese website!