Cursor this in C ++

Each object in C ++ has access to its own location through an important pointer called this pointer. The pointer this in C ++ is a hidden parameter to all member functions. So inside a member function, this pointer can refer to the calling object.

Each object in C ++ has access to its own location through an important pointer called this pointer. The pointer this in C ++ is a hidden parameter to all member functions. So inside a member function, this pointer can refer to the calling object.

The friend functions do not have this pointer, because friend is not a member of a class. Only member functions in C ++ have this this pointer.

Consider the following example to understand the concept of this pointer in C ++:

 #include using namespace std ; class Box { public : // phan dinh nghia Constructor Box ( double dai = 1.0 , double rong = 1.0 , double cao = 1.0 ) { cout << "Constructor duoc goi!" << endl ; chieudai = dai ; chieurong = rong ; chieucao = cao ; } double theTich () { return chieudai * chieurong * chieucao ; } int sosanh ( Box box ) { return this -> theTich () > box . theTich (); } private : double chieudai ; // chieu dai cua mot box double chieurong ; // chieu rong cua mot box double chieucao ; // chieu cao cua mot box }; int main ( void ) { Box Box1 ( 2.4 , 4.2 , 2.2 ); // khai bao box1 Box Box2 ( 4.5 , 2.0 , 3.2 ); // khai bao box2 if ( Box1 . sosanh ( Box2 )) { cout << "Box2 la nho hon Box1" << endl ; } else { cout << "Box2 la bang hoac lon hon Box1" << endl ; } return 0 ; } 

Compiling and running the above C ++ program will produce the following results:

Cursor this in C ++ Picture 1

According to Tutorialspoint

Previous article: Inline function in C ++

Next lesson: Cursor to class in C ++

3.5 ★ | 4 Vote | 👨 840 Views
« PREV POST
NEXT POST »