Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different placement of const keyword in method declarations?

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:

  1. const void f();
  2. void f() const;
  3. 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();
like image 209
user2083364 Avatar asked Dec 06 '22 05:12

user2083364


2 Answers

  1. const in this position declares the return type as const.
  2. 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).
  3. This is the above 2 combined.
like image 122
goji Avatar answered Dec 11 '22 12:12

goji


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!)

like image 26
codeling Avatar answered Dec 11 '22 10:12

codeling