views:

135

answers:

5

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?

A: 

Yes the compiler could, but it has no knowledge of your intent. And the original designers probably thought that supplying your intent was important.

Preet Sangha
+5  A: 

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?

Anon.
+1 for a spot-on answer.....
Prasoon Saurav
A: 

Having redundancy in like this in the language helps to insure that many programmer errors will end up being caught by the compiler.

John Knoeller
A: 

Another reason: If the function is static, it can't be overridden in derived classes. No polymorphism.

Scott Smith
That's virtual, not static. Both static and non-static base members can be hidden by derived classes, as std::fstream::rdbuf does, for example.
Roger Pate
@Roger: He's asking why methods that don't access any member variables aren't just automatically declared as `static` by the compiler. I'm saying that virtual methods might or might not access member variables, yet you wouldn't want the compiler automatically declaring them static.
Scott Smith
A virtual method, simply by virtue of being virtual, always implies access to member variables. Namely, the vtable. And since we're only talking about implicit static, and not implicit virtual, any method marked as virtual will never be eligible for automatic classification as static.
Rob Kennedy
+3  A: 

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.

AndreyT