Home > Backend Development > C++ > body text

Why Can\'t You Overload Static and Non-Static Functions in C ?

Susan Sarandon
Release: 2024-10-27 14:16:01
Original
330 people have browsed it

Why Can't You Overload Static and Non-Static Functions in C  ?

Overloading Static Functions with Non-Static Functions in C

In C , overloading static and non-static functions with the same name is not permitted. This is explicitly stated in the C standard, which prohibits overloading functions that differ only in return type or have the same name and parameter types if one of them is static.

Consider the following class:

<code class="cpp">class Foo {
    string bla;
    Foo() { bla = "nonstatic"; }

    void print() { cout << bla << endl; }
    static void print() { cout << "static" << endl; }
};</code>
Copy after login

While this class definition may seem plausible, it is invalid according to the C standard. Overloading static and non-static functions is prohibited because it would lead to ambiguity, as static functions can also be called using the object-member access (.) syntax.

For example, in the following code snippet:

<code class="cpp">Foo f;
f.print();</code>
Copy after login

It is unclear whether the static print function or the non-static print function should be called.

Furthermore, C does not provide a way to determine whether a function is being called statically or not, as in PHP. The this keyword, which points to the object for which the function is invoked, will always be non-null.

In Summary

Overloading static and non-static functions with the same name is not allowed in C . Additionally, there is no mechanism to differentiate between static and non-static function calls within a function body.

The above is the detailed content of Why Can\'t You Overload Static and 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!