Easy Tutorial
❮ Assignment Operators Overloading Cpp Function Call By Pointer ❯

C++ this Pointer

C++ Classes & Objects

In C++, each object can access its own address through the this pointer. The this pointer is an implicit parameter to all member functions. Therefore, within a member function, it can be used to point to the invoking object.

Friend functions do not have a this pointer, because friends are not members of the class. Only member functions have a this pointer.

The following example helps to better understand the concept of the this pointer:

Example

#include <iostream>

using namespace std;

class Box
{
   public:
      // Constructor definition
      Box(double l=2.0, double b=2.0, double h=2.0)
      {
         cout << "Constructor called." << endl;
         length = l;
         breadth = b;
         height = h;
      }
      double Volume()
      {
         return length * breadth * height;
      }
      int compare(Box box)
      {
         return this->Volume() > box.Volume();
      }
   private:
      double length;     // Length of a box
      double breadth;    // Breadth of a box
      double height;     // Height of a box
};

int main(void)
{
   Box Box1(3.3, 1.2, 1.5);    // Declare box1
   Box Box2(8.5, 6.0, 2.0);    // Declare box2

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

When the above code is compiled and executed, it produces the following result:

Constructor called.
Constructor called.
Box2 is equal to or larger than Box1

C++ Classes & Objects

❮ Assignment Operators Overloading Cpp Function Call By Pointer ❯