'static' for class functions of a C ++ class?

Why is a static keyword necessary at all?

Why can't the compiler determine if it is โ€œstaticโ€ or not?

Properly:

Can this function be compiled without access to non-stationary element data? Yes โ†’ static function. No โ†’ non-static function.

Is there a reason this is not deduced?

+4
source share
5 answers

If you expect the compiler to decide in-place whether it is static or not, how does this affect the external source files associated with the header file, which simply defines the method signatures?

+7
source

Compliance with static or non-static effects affects the type of function. Non-static member functions have an implicit this parameter, but not for static functions. For instance,

In other words, there is a significant qualitative difference between static and non-stationary member functions. The compiler cannot "output" this. This is a matter of intention of the author.

If I want (and need) my function to be non-static, I make it non-static, even if it does not have access to non-stationary members of the class. If the compiler hardly decides to make static static just because it does not have access to non-stationary members of the class, in general it will destroy the functionality of the code.

+4
source

Yes, the compiler could, but it does not know your intentions. And the original designers probably thought it was important to ensure your intentions.

+1
source

Having redundancy in this language in a language helps ensure that many programmer errors fall into the compiler.

0
source

Another reason. If the function is static, it cannot be overridden in derived classes. Polymorphism is absent.

0
source

Source: https://habr.com/ru/post/1302315/


All Articles