Home >Backend Development >C++ >Can Static and Non-Static Functions Be Overloaded in C ?

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

Linda Hamilton
Linda HamiltonOriginal
2024-10-28 18:58:30562browse

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>

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!

Statement:
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