There some answers for similar questions on stackoverflow, but all of them are incomplete or without comparison (with different examples). I saw at least 3 possible cases of declarations:
const void f();void f() const;const void f() const;What is the difference between them?
The only difference I have found is the following code works with (2) or (3) only:
const foobar fb;
fb.foo();
const in this position declares the return type as const.const in this position is only usable for member functions and means the function cannot / won't modify any member non-mutable variables (object constness).A const before the method name (as in point 1., and in point 3. of your question) refers to the return type. It means that the result of the function is non-modifiable; but there is a limit to when this const actually makes sense - basically, it usually only makes sense on user-defined types. What it means in the context of a void return type though, I have no idea at the moment. My best guess is that it is just ignored by the compiler.
A const after the method name (as in point 2. and 3.) makes the whole method const, meaning the method may not modify any members (except such declared mutable).
Since your foobar variable is declared const and thus may not be modified, only const methods on it can be called, that's why only 2. and 3. work (they both declare the method const; in 1. it's only the return type which is const!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With