Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'static' for c++ class member functions?

Why is the static keyword necessary at all?

Why can't the compiler infer whether it's 'static' or not?

As follows:

Can I compile this function without access to non-static member data? Yes -> static funcion. No -> non-static function.

Is there any reason this isn't inferred?

like image 278
anon Avatar asked Dec 18 '22 02:12

anon


2 Answers

If you expect the compiler to decide on the spot whether it's static or not, how does that affect external source files linking against the header file that just defines the method signatures?

like image 56
Anon. Avatar answered Dec 24 '22 02:12

Anon.


The propery of being static or non-static affects the function type. Non-static member functions have an implicit this parameter, while static ones don't, for one example.

In other words, there's a major qualitative difference between static and non-static member functions. The compiler cannot "infer" this. This is a matter of the author's intent.

If I want (and need) my function to be non-static, I make it non-static, even if it doesn't access any non-static members of the class. If the compiler suddently decides to make my non-static function static just because it doesn't access any non-static members of the class, in general case it will destroy the functionality of the code.

like image 27
AnT Avatar answered Dec 24 '22 00:12

AnT