this

The keyword this is a pointer to the current object, automatically provided by the C++ language.

 

The value of this is &currentObject, i.e. it is the address of the current instantiated object.

 

Useful for disambiguating identifier names, i.e. where two data members have the same name, the this pointer can be used to refer to the current object being pointed to.

 

private:

int myVar;

public:

void method(int myVar) {

this->myVar = myVar

}

 

In this case the rhs passed in parameter is assigned to the current object's myVar attribute within the scope of the method, which evades ambiguity towards the class's private myVar by use of the this-> pointer.

 

The current object can also be returned by dereferencing *this

 

return *this ;

 

Compile & Run:

myCube side: 6, volume: 216
myCube address using this: 0x28ff0c
which should be the same as using &: 0x28ff0c 

 

boing side: 6, volume: 216
boing address using this: 0x28ff08
which should be the same as using &: 0x28ff08

 

yourCube side: 5, volume: 125
yourCube address using this: 0x28ff04
which should be the same as using &: 0x28ff04

 

 

 

 

Another example:

(source)
Compile & Run:

180

Leave a Reply