Type of this Pointer

The this pointer's type can be modified in the function declaration by the const and volatile keywords. To declare a function as having the attributes of one or more of these keywords, add the keyword(s) after the function argument list.

Consider this example:

// type_of_this_pointer1.cpp
class Point
{
    unsigned X() const;
};
int main()
{
}

The preceding code declares a member function, X, in which the this pointer is treated as a const pointer to a const object. Combinations of cv-mod-list options can be used, but they always modify the object pointed to by this, not the this pointer itself. Therefore, the following declaration declares function X; the this pointer is a const pointer to a const object:

// type_of_this_pointer2.cpp
class Point
{
    unsigned X() const;
};
int main()
{
}

The type of this in a member function is described by the following syntax, where cv-qualifier-list is determined from the member functions declarator and can be const or volatile (or both), and class-type is the name of the class:

[cv-qualifier-list] class-type * const this

In other words, this is always a const pointer; it cannot be reassigned. The const or volatile qualifiers used in the member function declaration apply to the class instance pointed to by this in the scope of that function.

The following table explains more about how these modifiers work.

Semantics of this Modifiers

Modifier

Meaning

const

Cannot change member data; cannot invoke member functions that are not const.

volatile

Member data is loaded from memory each time it is accessed; disables certain optimizations.

It is an error to pass a const object to a member function that is not const. Similarly, it is an error to pass a volatile object to a member function that is not volatile.

Member functions declared as const cannot change member data — in such functions, the this pointer is a pointer to a const object.

Hinweis

Constructors and destructors cannot be declared as const or volatile. They can, however, be invoked on const or volatile objects.

See Also

Reference

this Pointer