Home > Backend Development > C++ > body text

Can Static and Non-Static Functions Be Overloaded in C ?

Linda Hamilton
Release: 2024-10-28 18:58:30
Original
478 people have browsed it

Can Static and Non-Static Functions Be Overloaded in C  ?

Overloading Static and Non-Static Functions in C

In C , it is not possible to overload a static function with a non-static function due to explicit prohibition in the C standard. This is stated in ISO 14882:2003 C Standard 13.1/2, which specifies that member function declarations with the same name and parameter types cannot be overloaded if any of them are static member function declarations.

Ambiguity with Static Function Invocation

Furthermore, calling a static function on an instance is possible in C . As per ISO 14882:2003 C Standard 9.4/2, a static member s of class X can be referred to using the qualified-id expression X::s, which means it is not mandatory to use the class member access syntax to access a static member.

This leads to ambiguity when calling static functions on instances. Consider the following example:

<code class="cpp">class Foo {
public:
    string bla;
    Foo() { bla = "nonstatic"; }
    void print() { cout << bla << endl; }
    static void print() { cout << "static" << endl; }
};</code>
Copy after login

In this example, calling f.print() is ambiguous because it is unclear whether to call the static or non-static print() function. While the C standard allows calling static member functions via this syntax, the presence of a non-static function with the same name introduces ambiguity.

Checking for Static Function Invocation

In contrast to PHP, C does not provide a direct way to check if a function is being called statically or not. The this keyword, which points to the object for which the function was invoked, will always point to an object, making it impossible to determine if the function is called statically or not.

The above is the detailed content of Can Static and Non-Static Functions Be Overloaded 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!