Share via


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, use the cv-mod-list grammar.

Syntax

  • cv-mod-list :
    cv-qualifier cv-mod-listopt
  • cv-qualifier :
    const
    volatile

Consider this example:

class Point
{
    unsigned X() const;
};

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:

class Point
{
    unsigned X() __far const;
};

The type of this is described by the following syntax, where cv-qualifier-list can be const or volatile, class-type is the name of the class:

cv-qualifier-listopt class-type  * const this

Table 8.2 explains more about how these modifiers work.

Table 8.2   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.

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