For the following code snippet,
class A{
const int a;
public:
A(): a(0){}
A(int m_a):a(m_a){};
A& operator =(const A &other);
};
A & A::operator =(const A &other)
{
const_cast<int&>(a) = other.a;
return *this;
}
what do the lines of
A & A::operator =(const A &other)
const_cast<int&>(a) = other.a;
mean? Or why this operator is defined this way? In other words, I feel confused about its usage and the way it is defined/written.
The
const_castremoves theconstfrom theconstmembera, thus allowing the assignment fromother.ato succeed (without theconst_castthe type ofawould beconst int, and thus it wouldn’t be modifiable).Probably the idea is that
ais initialized at class construction and can’t be modified “by design” in any other place, but the author of the class decided to make an exception for assignment.I have mixed feelings against this piece of code, very often the use of a
const_castis a symptom of bad design, on the other hand it can be logical to allow assignment but retain theconstfor all the other operations.