Home >Backend Development >C++ >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!