Home > Backend Development > C++ > body text

Why Can\'t Static Functions Be Overloaded with Non-Static Functions in C ?

Mary-Kate Olsen
Release: 2024-10-27 11:12:30
Original
739 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!