The keyword this is a pointer to the current object, automatically provided by the C++ language.
The value of this is ¤tObject, 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 ;
#include <iostream> using namespace std ; class Cube { private: int side ; public: //the prototypes Cube(int) ; //constructor float getSide() ; //getter float vol() ; //calc vol method void showThisAddress() { //display address cout << this << endl ; } Cube contrived(){ //return current object return *this ; } } ; //the implementations Cube::Cube(int side = 6){this->side = side ;} float Cube::getSide(){return side;} float Cube::vol(){return (side * side * side) ;} int main () { Cube myCube ; cout << "myCube side: " << myCube.getSide() ; cout << ", volume: " << myCube.vol() << endl ; cout << "myCube address using this: " ; myCube.showThisAddress() ; cout << "which should be the same as using &: " << &myCube << endl << endl ; Cube boing = myCube.contrived() ; //using return of above object to asssign cout << "boing side: " << boing.getSide() ; cout << ", volume: " << boing.vol() << endl ; cout << "boing address using this: " ; boing.showThisAddress() ; cout << "which should be the same as using &: " << &boing << endl << endl ; Cube yourCube(5) ; cout << "yourCube side: " << yourCube.getSide() ; cout << ", volume: " << yourCube.vol() << endl ; cout << "yourCube address using this: " ; yourCube.showThisAddress() ; cout << "which should be the same as using &: " << &yourCube << endl ; return 0; }
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
yourCube side: 5, volume: 125 |
Another example:
#include <iostream> using namespace std ; class Calc { private: int myVar; public: Calc() {myVar = 0;} //initial value Calc& Add(int x) {myVar += x ; return *this;} Calc & Sub(int x) {myVar -= x ; return *this;} Calc &Mult(int x) {myVar *= x ; return *this;} int getVal() {return myVar;} }; int main () { //declare myCalc object Calc myCalc; //chained call methods, passing in parameters and using *this to return values myCalc.Add(17).Sub(12).Mult(36) ; //display current value of myVar cout << myCalc.getVal() ; return 0; }
(source)
Compile & Run:
180 |