Consider a variation of your class A..
class A {
public:
void Foo() const;
void Moo();
private:
int m_nState; // Could add mutable keyword if desired
int GetState() const { return m_nState; }
void SetState(int val) { m_nState = val; }
};
const A *A1 = new A();
A *A2 = new A();
A1->Foo(); // OK
A2->Foo(); // OK
A1->Moo(); // Error - Not allowed to call non-const function on const object instance
A2->Moo(); // OK
The const
keyword on a function declaration indicates to the compiler that the function is contractually obligated not to modify the state of A. Thus you are unable to call non-const
functions within Foo() nor change the value of member variables.
To illustrate, Foo() may not invoke SetState() as it is declared non-const
, GetState() however is ok b/c it is explicitly declared const
. The member m_nState may not be changed either unless declared with the keyword mutable
.
One example of this usage of const
is for 'getter' functions to obtain the value of member variables.
@1800 Information: I forgot about mutable!
The mutable
keyword instructs the compiler to accept modifications to the member variable which would otherwise cause a compiler error. It is used when the function needs to modify state but the object is considered logically consistent (constant) regardless of the modification.