1

Ive searched through the archived posts but I couldnt find anything similar.

Just a simple question: whats the best practice in declaring inspecting functions like:

int foo(int a) const { return a+1; }

Im referring to the const keyword, do you usually declare it at the end of an inspecting function? Im just asking because I usually do, even if 99% I wont declare any const class.. I just keep on tellin myself that it could save me some time if I ever should need to, but I was wondering if anybody else really cares about declaring const functions or if Im just paranoid about typesafe code

user815129
  • 2,236
  • 2
  • 20
  • 40

3 Answers3

6

Assuming that you are talking about member functions (non member functions cannot be const ever), you should write const-correct code always, and that means that each and every function that does not modify the visible state of the object should be const.

Even if you don't ever create a constant object of the type, in many cases you will pass the object to a function through const references and in that case, only const member functions can be called on the object (Incidentally this means that you should pass the object by constant reference to any function that does not need to change the state of the received object)

David Rodríguez - dribeas
  • 204,818
  • 23
  • 294
  • 489
1

Yes, of course you should if you want your program to support const correctness.

Const correctness has a way of propagating through your program once you begin declaring instances as const. As program complexity and your use of const increases, then you will either:

  • encounter many compiler errors when using const objects if you do not add them now
  • or your program will build without (or fewer) errors once you favor using const in the appropriate places.
  • or you may end up avoiding const for some time - which is (IMO) not a good road to go down if you want to improve your designs.

Over time, many of us have learned to use const in more than 1% of our code.

justin
  • 104,054
  • 14
  • 179
  • 226
1

The const appended at the end of the function declaration and definition indicates a contract between the caller of the function and the function that the function will not modify any members of that class.

So if your function provides guarantee for such an const-correctness contract you should extend it to users of your function.

Alok Save
  • 202,538
  • 53
  • 430
  • 533