Home > Article > Backend Development > Why Can't I Overload Functions Based on the Constness of Non-Pointer/Non-Reference Arguments in C ?
Overloading Functions with Const Arguments
In C , function overloading allows multiple functions with the same name to be used depending on the arguments passed to them. However, in certain situations, overloading a function based solely on the constness of a non-pointer, non-reference type is not feasible.
Consider the following code snippet:
class Test { public: int foo(int); int foo(const int) const; };
In this example, our intent is to overload the foo function, where one function is a const function and the other is not. Yet, this code results in a compilation error stating that the function cannot be overloaded.
Why does this occur?
The compiler cannot disambiguate which function to call despite the presence of the const keyword on the argument. When passed by value, the value is copied regardless of the argument's constness. Therefore, the const on the argument is only relevant within the function definition itself.
As a result, the compiler is unable to determine which version of the foo function to call based solely on the constness of the argument.
The above is the detailed content of Why Can't I Overload Functions Based on the Constness of Non-Pointer/Non-Reference Arguments in C ?. For more information, please follow other related articles on the PHP Chinese website!