Home arrow C++ arrow Page 3 - Const Correctness in C++

Const Correctness in C++

One of the biggest advantages of programming in C++ is that you can do the same thing in a variety of ways. At least in theory the compiler lets you do this. Under these circumstances, the difference between a good programmer and a very good programmer lies in the methods they use to accomplish specific tasks. Coding with const correctness in mind is one of the recommended techniques that raises you to the level of a very good programmer. Itís that important to grasp this concept.

Author Info:
By: Gabor Bernat
Rating: 3 stars3 stars3 stars3 stars3 stars / 6
October 28, 2008
  1. · Const Correctness in C++
  2. · Constant Variables
  3. · Const in Functions and in Classes
  4. · Conclusion

print this article

Const Correctness in C++ - Const in Functions and in Classes
(Page 3 of 4 )

Another observation we need to make is that C++ can resolve automatically the conversion of a variable from non-const to const, but not the reverse. This will allow us to call functions that take const parameters with non-const variables. Also, in this way eventual programming design errors can be eliminated.

Look at the code snippet below as it presents a brief example of how this technique will be used in classes. Explanations follow:

class point



int& x () const;

const int& x () const;

int& y () const;

const int& y () const;

void setNewValues (const int& newX, const int& newY);

bool isEqual (const int* const newX,

const int* const newY)const;



int x;

int y;

mutable string errorMessage;



Implementation of a few:

int& point::x () const


return x;



bool point:: isEqual (const int* const newX,

const int* const newY) const


if( !newX && !newY)

errorMessage = ("Invalid pointers in an isEqual");


return *newX = x() && *newY == y();



Now here we have almost all of what you should know about const correctness in classes. The class represents a point simulation in 2D. First, I will explain why we are making the two intern variables private and after that returning const references to it. The explanation is quite simple. Read below!

Have you ever faced a situation where you just observed that a variable changed its value and you have one idea where to search for the modification in the code? In fact anyone could easily access the class's members from anywhere, so now you should debug all of the code and find where the mistake was made. You don't need to do that with this approach; now we can put a break point in the x function, and at every little modification this modification must be called. If we use this approach in the class also, it will result in easily debuggable code, less time wasted, and more efficiency.

But to switch back to our subject, probably you observed that we have written const after a few functions. If you look closer you'll also detect that this is true only for functions where no modifications are made for the members. And this is what we mean by const functions in classes.

You guarantee (and the compiler will make sure of it) that not a single modification can or will be made for the members of the class. At least, you do this at first glance. Here is the exception: the mutable keyword. The mutable is what defies all this. Any member declared mutable can be modified within a const function. This is perfect if we want to implement, for example, an error reporting string in the class; errors could occur in a const function also, after all. Consider the isEqual function shown earlier. 

Bear in mind that you can't call any of the non-const functions inside of a function like this. All functions called within must be const to maintain the rule that not a single one (expecting the mutable ones, but that's the wonder of it) will have different values compared to the start at the end of calling the respective task.

At this moment you should also comprehend why we wrote two x() functions. This way C++ will complete const overloads, and whenever needed, it's going to call the const one, which is only for an equality check. The const reference ensures that the type won't be messed with anywhere during the call, and also the non-const type will still let us modify the members anywhere in the program.

You may have some situations when you know that a function won't change the value of a const type, but you can't call it, as the function isn't made const. For these special cases, use the const_cast. The cast lets you create a temporary non-const type to it, so you can force the function to call it. Be conscious, though, that when the members are going to be modified, the result can be undefined.

If you know a little STL you've probably figured out by now what the const_iterator means. Yes, you are right. This type of iterator makes const the type at which it's pointing, and due to this no modification can be made to the members (not to the iterator, just to what it is pointing, unless you declared the iterator itself as const). Use this type of iterator whenever you need to see the members in a container in a const function but are now willing to modify a single member.

blog comments powered by Disqus

- Intel Threading Building Blocks
- Threading Building Blocks with C++
- Video Memory Programming in Text Mode
- More Tricks to Gain Speed in Programming Con...
- Easy and Efficient Programming for Contests
- Preparing For Programming Contests
- Programming Contests: Why Bother?
- Polymorphism in C++
- Overview of Virtual Functions
- Inheritance in C++
- Extending the Basic Streams in C++
- Using Stringstreams in C++
- Custom Stream Manipulation in C++
- General Stream Manipulation in C++
- Serialize Your Class into Streams in C++

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 

Developer Shed Affiliates


© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials