[class.this] (original) (raw)

11 Classes [class]

11.4 Class members [class.mem]

11.4.2 Non-static member functions [class.mfct.non-static]

11.4.2.1 The this pointer [class.this]

In the body of a non-static ([class.mfct]) member function, the keyword this is a prvalue whose value is a pointer to the object for which the function is called.

The type of this in a member function whose type has a cv-qualifier-seq cv and whose class is Xis “pointer to cv 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++; } };

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 becausethis is a pointer to const; that is, *this hasconst type.

end example

]

[ Note

:

Similarly, volatile semantics apply in volatile member functions when accessing the object and its non-static data members.

end note

]

[ Example

:

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

The call y.g() is ill-formed because y is constand s​::​g() is a non-const member function, that is,s​::​g() is less-qualified than the object expression y.

end example

]

[ Note

:

Constructors and destructors cannot be declared const, volatile, or const volatile.

However, these functions can be invoked to create and destroy objects with cv-qualified types; see [class.ctor] and [class.dtor].

end note

]