Using const

Another issue with pointers you need to consider is that they are volatile; they provide indirect access to the object itself and can be the source of inadvertent and difficult to track changes to the object. If you are passing a pointer for efficiency (to avoid copying large temporary objects on the stack) be sure to use the keyword const.

The keyword const can be used with pointers in a variety of ways:

const Employee* pOne;
Employee* const pTwo;
const Employee* const pThree;

It is important to understand the differences in these three declarations. pOne points to a constant Employee — you can not use this pointer to change the values of the Employee object to which it points. pTwo is a constant pointer to an Employee — you can not reassign this pointer to point to anything else. pThree has both restrictions.

The goal, again, is to constrain your behavior and to enlist the compiler in finding your bugs. If you are passing by reference only for efficiency, then you should declare the pointer to point to a constant object. If you then attempt to modify that object using the pointer, the compiler will flag your error and save you many hours of aggravation.

Declaring a member function constant declares that you will not use that member function to modify the object. Here's how it works. Every member function has an implicit and invisible parameter, which is the this pointer. The this pointer points to the object itself, and when you refer to a member variable or a method from within a member method, the compiler uses the invisible this pointer to resolve the reference. Thus, if you write:

void Employee::SomeFunction()
{
   myAge = 7;
}

The compiler translates this into:

void Employee::SomeFunction(Employee * this)
{
   this->myAge = 7;
}

If you declare SomeFunction() to be const, the this pointer is set to be constant. If you wrote:

void Employee::SomeFunction() const
{
   myAge = 7;
}

This would be translated to:

void Employee::SomeFunction(const Employee * this)
{
   this->myAge = 7; // compiler error!
}

Since it is not legal to use a pointer to a constant object to change that object (e.g. to set a member variable's value), this will be flagged as a compile-time error. Incidentally, this is why static member methods cannot be declared as constant. Static member methods do not have a this pointer — they are not tied to a particular object.

© 1998 by Wrox Press. All rights reserved.