In C , static member methods are typically called using the class name itself, rather than an instance of the class. However, there arises a question: can static member methods be invoked on class instances?
The given code snippet demonstrates an intriguing behavior:
class Test { public: static void DoCrash(){ std::cout << "TEST IT!" << std::endl; } }; int main() { Test k; k.DoCrash(); // calling a static method like a member method... }
On Visual Studio 2008 SP1, this code successfully compiles and outputs "TEST IT!". Contrary to the usual expectation, a static method is seemingly invoked on an instance of the class.
1. Are You Wrong? Is the Code Correct?
Based on the C standard, calling a static member method on an instance is not incorrect. The standard explicitly states in 9.4 (Static Members):
"A static member of class X may be referred to using the qualified-id expression X::s; it is not necessary to use the class member access syntax (5.2.5) to refer to a static member."
In other words, it is not a requirement to use the class name to access static members. Class member access syntax is permissible, but the object-expression is evaluated in that case.
2. Why Is This Allowed?
The standard allows for static members to be invoked on instances to facilitate the use of "static or not" methods in templates. Templates often require the ability to call a function without knowing whether it's static or not. By allowing static member invocation on instances, the compiler can always determine the correct function to call, regardless of its static status.
The above is the detailed content of Can You Call a Static Member Method on a Class Instance in C ?. For more information, please follow other related articles on the PHP Chinese website!