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 raise you to the level of a very good programmer. It’s that important to grasp this concept.
It may seem to be just another pain in the neck at first glance. You could say “oh yes; it’s not enough that my boss just hit me with lots of coding standards, now I got another issue to watch out for.” If you don’t know what coding standards are and how they can help you, please read this article. It sums up briefly the idea behind them.
But let’s get back to const correctness. Good and excellent programmers use it not because it’s trendy; it’s because it helps cut the debugging time of code to a minimum and brings issues closer to the compiler. Generally, in coding, it is recommended that you bring any mistakes or errors closer to the compiler. This way the compiler tells you instantly if something is wrong and you evade hours of debugging. For example, you might write in an “if” statement first the constant and only after it the variable:
if (1 == alfa) // instead of alfa == 1
This way, if you for some reason (maybe a bad day or a stressful boss) put only one equal sign, the compiler will warn you at compile-time, and you can correct it right away without wasting countless minutes searching for the problem that makes the function/program work, but not the way you were expecting it to. Const correctness can be perceived as a tool or trick in that sense.
If you are interested in investing the time to read more about const correctness, I welcome you aboard. There are few if any prerequisite skills needed for understanding this technique or this article; maybe some basic C++ familiarity, and an understanding of the object-oriented programming method as well.
Constant, according to the Free Online Dictionary, means: Unchanging in nature, value, or extent; invariable. This pretty much tells you all you need to know about them in the beginning. Basically, C++ inherited this from the C language. There already, a constant variable was nothing more than one whose value remained constant throughout the execution of the program once a value had been assigned to it upon initialization.
Because writing a program can be time-consuming, and programmers are naturally lazy and prefer to accomplish much without writing much, in C/C++ the constant keyword has been reduced to const. As C/C++ includes more than just plain variables, the const keyword has been introduced for pointers and references as well. Below I will show you an example of each one and explain them afterward.
- int I = 1;
- const int I = 2;
- const int* I = 3;
- int const * I = 3;
- int* const I = 2;
- const int* const I = 1;
- const int& I = 2;
- int& const I = 2;
- typedef int_co_ref int&;
10.int_co_ref const I = 2;
Now there we have all of the combinations possible, but what does each of them mean? Well, the first one should be obvious if you are still reading this text. As for the second one the situation should be same. All we did was declare a variable that is constant-unchangeable and initialize it with the value 1. From the point of declaring the variable through any point where the variable’s declaration is still valid (aka in the interior of the scoop (parenthesis – {} you declared), we can use it instead of writing the number 1.
The third example represents a pointer pointing to a const variable. Once it is created, you can’t modify the variable to which it points, but you are free to assign to the pointer a different variable. Here we can also include the fourth as it is the same; the compiler lets us write the const keyword where we wish.
Now the fifth example is more intriguing. We create a pointer that is a const. That means that it won’t be able to change the variable through the pointer. However, through a different pointer or through the variable itself we are free to make any changes. Simply put, we have a pointer that, once assigned, cannot be changed, but that applies only to the pointer and not to the variables related to it.
The last one is the const from all points of view. Put the second and fifth examples together and you will get one that looks just like the sixth. A const (unchangeable) pointer points to a constant variable. This is an excellent method to use if you want to be sure that the input data won’t change in a function.
The const reference is something that isn’t. Okay now I know that sounds awkward, but the truth is that you can’t create one like this. Simply put, it isn’t correct grammatically. And to underline my statement, the eighth row in the upper code snippet will return a syntax error. Of course you can create one with rows 9 and 10, but the compiler would ignore it. The const here is redundant and will be ignored by the compiler.
The the upper statements are all true because a reference in its essence is a binder to a variable. Once you bind it to one, you cannot bind it to another; it can’t refer to another variable. The reference is in its nature const.
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
{
public:
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;
private:
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.
If you read my article about Coding standards you should already know what benefits it brings to your programming “kitchen.” Const correctness promises to offer at least as many benefits if it is done right. You can get a code where the modification of every type can be tracked effortlessly.
But think it over; don’t use const everywhere just because you can do it. Use it only where you are absolutely sure that no modification will be made. Write functions as generally as you can; if the function can have a const overload, make it. However, be aware of local variables and don’t start returning const references/pointers to them; local variables are destroyed.
Only one question remains to be answered: when is it best to start implementing const capabilities in a program? The most accurate answer would be “before you start writing a single line.” The functions in your head should be born with const correctness. It can be hard at the beginning (especially to not abuse it), but once you get it, it will became second nature, and spare you countless hours of debugging.