This Pointer

Each individual object in C++ is given access to its own address via an important pointer, which is known as this pointer. The this pointer can be defined as an implicit parameter to all the member functions. Hence, when used within a member function, it may be used to refer to the invoking object.

Friend functions are not given access to a this pointer. The reason behind this is that friends are not members of a class. Only member functions are allowed to have a this pointer.

Now we will look at the following example to get a better understanding of the concept of the this pointer.

#include <iostream>
 
using namespace std;

class Room {
   public:
      // Constructor is being defined here
      Room(float a = 5.0, float b = 4.0) {
         cout <<"Constructor called." << endl;
         length = a;
         breadth = b;
      }
      float Area() {
         return length * breadth;
      }
      int Check(Room room) {
         return this->Area() > box.Volume();
      }
      
   private:
      float length;     
      float breadth;    
};

int main(void) {
   Room Room1(2.5, 2.1, 5.2);    // Room1 Declaration 
   Room Room2(7.0, 5.0, 4.4);    // Room2 Declaration 

   if(Room1.compare(Room2)) {
      cout << "Room2 is smaller than Room1" <<endl;
   } else {
      cout << "Room2 is equal to or larger than Room1" <<endl;
   }
   
   return 0;
}

 

Output:

Constructor called.
Constructor called.
Room2 is equal to or larger than Room1