9 Classes [class]

9.3 Member functions [class.mfct]

9.3.2 The this pointer [class.this]

In the body of a non-static ([class.mfct]) member function, 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*, if the member function is declared volatile, the type of this is volatile X*, and if the member function is declared const volatile, the type of this is const volatile X*. Note: thus in a const member function, the object for which the function is called is accessed through a const access path.  — end note ] [ Example:

struct s {
  int a;
  int f() const;
  int g() { return a++; }
  int h() const { return a++; } // error
};

int s::f() const { return a; }

The a++ in the body of s::h is ill-formed because it tries to modify (a part of) the object for which s::h() is called. This is not allowed in a const member function because this is a pointer to const; that is, *this has const type.  — end example ]

Similarly, volatile semantics ([dcl.type.cv]) apply in volatile member functions when accessing the object and its non-static data members.

A cv-qualified member function can be called on an object-expression ([expr.ref]) only if the object-expression is as cv-qualified or less-cv-qualified than the member function. [ Example:

void k(s& x, const s& y) {
  x.f();
  x.g();
  y.f();
  y.g();                        // error
}

The call y.g() is ill-formed because y is const and s::g() is a non-const member function, that is, s::g() is less-qualified than the object-expression y.  — end example ]

Constructors ([class.ctor]) and destructors ([class.dtor]) shall not be declared const, volatile or const volatile. [ Note: However, these functions can be invoked to create and destroy objects with cv-qualified types, see ([class.ctor]) and ([class.dtor]).  — end note ]