Reputation: 567
I went through the already existing thread on this topic and wasn't convinced with the explanation.
What I could pick up from there was:
When a non-static member function is declared const
, the restriction is imposed on this this
pointer. As static member functions donot involve the this
pointer, they cannot be declared const
.
Is that it? Doesn't sound too convincing to me. I mean, I'm not questioning why it's so. I just want to to the reason why.
Upvotes: 0
Views: 333
Reputation: 182753
The reason the const/non-const distinction for functions is important is that there are contexts in which it is not legal to call a non-const function. So the distinction can be used to enforce invariants.
For example, if you pass a non-const reference to a function, if your class is properly designed, you are guaranteed that the function can't change the value of the thing the reference refers to. This allows you to avoid copies.
Also, a non-const reference can't bind to a temporary. This permits functions to signal whether they return values through references or just take a value. You will get an error at compile time if you inadvertently ignore a returned value because a temporary was created unexpectedly.
None of this would apply to static functions because there is no context in which you would be prohibited from calling them. So the entire rationale for the distinction does not exist with static functions.
Upvotes: 1
Reputation: 119089
A const
non-static member function is allowed to modify local, static, and global variables; it just isn't allowed to modify members of its class through the this
pointer (implicitly or explicitly). A const
static member function, therefore, would be allowed to modify local, static, and global variables, just like a non-member function. This would make the const
meaningless.
If you want to write a function that isn't allowed to modify any non-local variables at all, you can declare it constexpr
, although that also imposes additional restrictions.
Upvotes: 4