Changing things that shouldn't be changed is one of the most common sources of error.
It is therefore worthwhile specifying const because it prevents you from doing something wrong. Why would you want to give that up?
const double PI = 3.14159265358979;
PI=4; // generates a compiler error (good)
There are some problems with the c++ notation, because a constant can only be initialized, not assigned the first time, and sometimes, you don't have the value at initialization time.
class A {
private:
const int num;
public:
A(int x, int y) : num(0) { // oops, I don't yet know what num should be
while ( ... ) {
}
num = ...;
}
};
The way out of this one is to define a private function that computes the value of num
but sometimes that means that instead of one clean block of code in the constructor, you are forced to split it into sections in awkward ways, just so you can initialize the variable.
class A {
private:
const int num;
int computeNum(int x, int y) { ... }
public:
A(int x, int y) : num(f(x,y)) {
}
};
Sometimes, you have a value that is generally supposed to be const, but you want to selectively override that when it semantically makes sense. For example, social security numbers don't change, unless your identity is stolen. So you have just one method, called createNewSSN() which changes the otherwise constant ssn
class Person {
private:
const int ssn;
public:
Person(int ssn_) : ssn(ssn_) {}
void createNewSSN(int newssn) {
log << "Changed SSN: " << ssn << " to " << newssn << "\n";
*(int*)&ssn = newssn; // trust me, this is a special case....
}
};