Home > Backend Development > C++ > body text

Can You Call a Static Member Method on a Class Instance in C ?

Patricia Arquette
Release: 2024-11-06 03:51:02
Original
264 people have browsed it

Can You Call a Static Member Method on a Class Instance in C  ?

C Static Member Method Invocation on Class Instance

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...
}
Copy after login

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!

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!