Sign in to follow this  
  • entries
    375
  • comments
    1136
  • views
    297567

If you are working in C++

Sign in to follow this  

62 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.
Sign in to follow this  


2 Comments


Recommended Comments

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?

Share this comment


Link to comment
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.

Share this comment


Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now