Home  >  Article  >  Backend Development  >  Can you invoke static member methods via class instances in C ?

Can you invoke static member methods via class instances in C ?

DDD
DDDOriginal
2024-11-08 02:59:02140browse

Can you invoke static member methods via class instances in C  ?

C Static Member Method Invocation via Class Instance

A peculiar coding practice has emerged in certain C codebases: invoking static member methods via class instances. This unconventional approach raises several questions regarding its validity and rationale.

Is it Standard-Compliant?

Contrary to common knowledge, the C standard explicitly allows static member methods to be called using both class instances and qualified class names. Section 9.4 of the C 03 standard clarifies that while it's unnecessary to utilize class member access syntax, it remains permitted.

Implementation Rationale

The standard provides limited insight into why this unique calling mechanism is allowed. However, one possible reason is to accommodate templates that allow switching between static and non-static method invocations.

Example Illustration

Consider the following code snippet that demonstrates the permissible use of invoking a static method via a class instance:

class Test {
public:
    static void DoCrash() { std::cout << "TEST IT!" << std::endl; }
};

int main() {
    Test k;
    k.DoCrash(); // Calling a static method through an instance

    return 0;
}

When compiled, the program will output "TEST IT!" to the console. This behavior corroborates the standard's allowance of invoking static methods via class instances.

The above is the detailed content of Can you invoke static member methods via class instances 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