Possible Duplicate:
is const (c++) optional?
Constant Member Functions
I have seen different posts around about int a() const. My question is exactly why do we want to put the const keyword there? I know that it prevents us from making changes on members of the class the function is in, but so what?
We could just write a comment above the function and tell the coder not to make any changes to the class itself inside the function, but why do we really care about the const after the void declaration? In which scenarios may there be a better way to use for example int a() const instead of just int a() and does the compiled code change at all?
It does make a difference. Consider
Ato be a class with aprint()method. Then this:only compiles is
printis defined asconst.Of course, the main reason is to prevent any changes to the object inside the class. The
is just wishful thinking. This doesn’t really happen. So if someone doesn’t read the comment (or does and ignores it), you’ll get compiler errors.
There’s also the benefit of optmization – the compiler can better parallelize tasks on
constobjects because it can assume they don’t change between operations on them.