The general rule for using the const keyword is:
const, you should use const.
Contents |
Use constants instead of #defines, as constants are type checked:
const int WIDTH = 800;
Preferably define them in classes:
class Thing {
public:
static const int MAX_SIZE; // access by Thing::MAX_SIZE
};
and set the value in the implementation:
const int Thing::MAX_SIZE = 100;
When you don't want a variable to change beyond its initialization, make it constant:
const int x = foo.getValue(); // x++; <- this is illegal
const int* x; // a pointer to a constant int* const x = &y; // a constant pointer int const* const x = &y; // a constant pointer to a constant :)
Typical usage:
int calculateSomething(const int& x) // x will not be changed in calculateSomething() const int* getSomething(void) // get a pointer to a constant
Concerning constant objects:
class Thing {
public:
void doSomething(int x) const; // can be called from a constant object
};
...
const Thing thing;
thing.doSomething(0);
The following means that x won't be changed inside the method. As x is passed-by-value this does not mean anything to a user of the interface.
void doSomething(const int x) { }
Replace by this code, as not to confuse the interface:
void doSomething(int xc) {
const int& x = xc;
// use x but don't change it
}