Home >Backend Development >C++ >Why Can\'t Static Functions Be Overloaded with Non-Static Functions in C ?
Can't Overload Static Functions with Non-Static Functions in C
While many programming languages allow overloading functions based on static or instance methods, C explicitly prohibits this behavior. The C Standard 13.1/2 states that member functions with the same name and parameter types cannot be overloaded if any of them is static.
<code class="cpp">class X { static void f(); void f(); };</code>
In the example above, the two declarations of f() are considered ill-formed by the standard.
Ambiguity in Calling Static Functions on Instances
Even if function overloading were allowed in this scenario, there would still be ambiguity when calling a static function on an instance. The C Standard 9.4/2 permits static members to be called using both the qualified-id (e.g., X::f()) and the class member access syntax (e.g., g().reschedule()). Thus, in the following code, it is unclear whether the static or non-static print() function should be called:
<code class="cpp">class Foo { void print() { cout << "nonstatic" << endl; } static void print() { cout << "static" << endl; } }; Foo f; f.print(); // Ambiguous: static or non-static?</code>
Checking if a Function is Called Statically
Unlike in PHP, where you can check if the this variable is defined to determine whether a function is called statically, C does not provide this capability. The this keyword always points to an object and is never NULL, so you cannot use it to distinguish between static and instance calls.
The above is the detailed content of Why Can\'t Static Functions Be Overloaded with Non-Static Functions in C ?. For more information, please follow other related articles on the PHP Chinese website!