this pointer

< cpp‎ | language
Revision as of 13:12, 9 February 2014 by Cubbi (Talk | contribs)

Inside non-static member function, holds a pointer to the class object from which the function was invoked.

The type of this pointer is cv T* const where T is the class name and cv refers to the cv specifiers of the function the pointer is used in. For example:

Function signature Type of this
void T::foo()                T* const this;
void T::foo() const          const T* const this;
void T::foo() volatile       volatile T* const this;
void T::foo() const volatile const volatile T* const this;


class T
    int x;
    void foo()
        this->x = 5; // this used explicitly
        x = 6; // same as this->x = 6;
    void foo() const
        this->x = 7; // Error: *this is constant
    void foo ( int x )
        // parameter x shadows the attribute with the same name
        this->x = x; // unqualified x refers to the parameter, but the attribute is still accessible using the this pointer 
    T& operator= ( const T& b )
        x = b.x;
        return *this; // this is often used when a reference to the current object is needed
    void bar ( const T& b )
        // two ways to call class operators using this 
        *this = b;
        this->operator= ( b );
    void bar()
       // methods can be called even when there's no object
       // the this pointer can be seen like an additional parameter implicitly passed
       if ( this == NULL )
T* pointer = reinterpret_cast<T*>(123);
pointer->bar(); // bar is called with 123 (0x7B) as value for this