C++ Programming/Classes/this

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search

[edit] this pointer

this is a C++ keyword that acts as a pointer to a 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 what a pointer does. The this pointer is only accessible within nonstatic member functions of a class (or a 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 you debug code in a GUI compiler with some way of viewing the current variables, 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 x;
public:
    Foo(){  x=5;  };
    int getData() 
    {   
        return this->x;  // this is provided by the compiler at compile time
    }
};
 
int main()
{
    Foo Example;
    int temp;
 
    temp = 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 x;
public:
    Foo(){  x=5;  };
    int getData()          
    {                            
        return x;  
    }
    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->x = RHS.x;        // 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.