• entries
375
1136
• views
297750

# If you are working in C++

66 views

then use the 'const' keyword as much as you can, particularly at low levels.

Leaving it out at a low level tends to 'infect' higher levels of code with non-constness.

It's worth noting that constness is a valid differentiator for overloaded functions, i.e. you can overload a function with no arguments to create a const version:

Object* GetObject();const Object* GetObject() const;

This is of course not valid for functions without a 'this' pointer to be made const - non-member functions and static member functions, I mean. Instance methods are where it's at.

So why should we do this? I do try and make habit of doing it, but am not really sure why I'm doing it. Some far-flung note I read somewhere I think... What are your reasons for using the const keyword?

Well, first and foremost, it strengthens the intent of the method. Declaring a member function as const states, 'I will not modify my object.' To know that information through any other means, you'd have to look at the function implementation.

Secondly, it aids the compiler a bit - it can make certain optimizations if it knows that something is read-only (e.g. it knows that a const object will not have changed value between two comparisons).

In general, the more things you have that are altering your program's state, the more complex it becomes, the more bugs appear, and the harder it becomes to debug, as more and more systems are interacting. That's why 'nailing down' the parts of your program that don't change any state is helpful; it allows the parts that do change state to stand out more.

Oh, and of course, const_cast<> is evil.