C++ Programming/Classes/this

this pointer

edit

The this keyword acts as a pointer to the class being referenced. The this pointer acts like any other pointer, although you can't change the pointer itself. Read the section concerning pointers and references to understand more about general pointers.

The this pointer is only accessible within nonstatic member functions of a class, union or struct, and is not available in static member functions. It is not necessary to write code for the this pointer as the compiler does this implicitly. When using a debugger, you can see the this pointer in some variable list when the program steps into nonstatic class functions.

In the following example, the compiler inserts an implicit parameter this in the nonstatic member function int getData(). Additionally, the code initiating the call passes an implicit parameter (provided by the compiler).

class Foo
{
private:
    int iX;
public:
    Foo(){ iX = 5; };

    int getData() 
    {   
        return this->iX;  // this is provided by the compiler at compile time
    }
};

int main()
{
    Foo Example;
    int iTemp;

    iTemp = Example.getData(&Example);  // compiler adds the &Example reference at compile time

    return 0;
}

There are certain times when a programmer should know about and use the this pointer. The this pointer should be used when overloading the assignment operator to prevent a catastrophe. For example, add in an assignment operator to the code above.

class Foo
{
private:
    int iX;
public:
    Foo() { iX = 5; };

    int getData()          
    {                            
        return iX;  
    }

    Foo& operator=(const Foo &RHS);
};

Foo& Foo::operator=(const Foo &RHS)
{
    if(this != &RHS)
    {    // the if this test prevents an object from copying to itself (ie. RHS = RHS;)
        this->iX = RHS.iX;     // this is suitable for this class, but can be more complex when
                               // copying an object in a different much larger class
    }

    return (*this);            // returning an object allows chaining, like a = b = c; statements
}

However little you may know about this, it is important in implementing any class.