A
const
modifier on a method prevents you from modifying any member variables from within that method. In other words, if you declare a method as
const
, you can pretend that every single member variable belonging to that class is declared
const
, effectively making the internals of the class read-only for that particular method.
Note that you can still create and modify local variables within const methods (see GetDiameter below), the only restriction is that you cannot modify member variables (such as m_radius, below).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
class Circle {
public:
void SetRadius(int radius) { // no const modifier on method, so it is ok to modify m_radius here
m_radius = radius;
}
int GetRadius() const { // const modifier effectively makes m_radius (and any other member variables const)
// m_radius = 10; // This would cause a compiler error because of the method's const modifier
return m_radius;
}
int GetDiameter() const {
int diameter = GetRadius() * 2; // It is ok to create local variables
return diameter;
}
private:
int m_radius;
};
| |
Edit: In order to answer part two of your question, you should also know the following.
If a method has a
const
modifier, it cannot call any methods which do *not* have
const
modifiers. In other words, you would not be able to cheat the
const
system by calling SetRadius() from within GetRadius in order to modify m_radius indirectly.