What is the meaning of a const at end of a member function? [duplicate]

It means that *this is const inside that member function, i.e. it doesn’t alter the object.

The keyword this is a prvalue expression whose value is the address of the object for which the function is called. The type of this in a member function of a class X is X*. If the member function is declared const, the type of this is const X*. [section 9.3.2 §1]

In a const member function, the object for which the function is called is accessed through a const access path; therefore, a const member function shall not modify the object and its non-static data members. [section 9.3.2 §2]

This means that a const member function can be called on a const instance of the class. A non-const member function can’t be called on [1]a const object, since it could potentially try to modify it.


[1] Note: a temporary is not a const object unless it’s of const type.

Leave a Comment