Changing things that should not be changed is one of the most common sources of error. Therefore, it is worth specifying const, because it prevents you from doing something wrong. Why would you do this?
const double PI = 3.14159265358979; PI=4;
There are some problems with C ++ notation, because a constant can be initialized, but not assigned for the first time, and sometimes you do not matter during initialization.
class A { private: const int num; public: A(int x, int y) : num(0) {
The way out of this is to define a private function that calculates the num value, but sometimes this means that instead of a single clean block of code in the constructor, you are forced to partition it uncomfortably, just so that 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 should usually be const, but you want to selectively redefine it when it semantically makes sense. For example, social security numbers do not change unless your identity is stolen. Thus, you have only one method called createNewSSN (), which changes the constant 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;
source share