C++ this Pointer


Advertisements

Every object in C++ has access to its own address through an important pointer called this pointer. The this pointer is an implicit parameter to all member functions. Therefore, inside a member function, this may be used to refer to the invoking object.

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

Let us try the following example to understand the concept of this pointer −

#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
cpp_classes_objects.htm

Useful Video Courses


Video

C++ Online Training

154 Lectures 11.5 hours

Arnab Chakraborty

Video

Learn C++ Pointers with Visual Studio 2017

14 Lectures 57 mins

Kaushik Roy Chowdhury

Video

Modern OpenGL C++ 3D Game & 3D Rendering

30 Lectures 12.5 hours

Frahaan Hussain

Video

Cocos2d-x v3 C++ - Beginning Game Development

54 Lectures 3.5 hours

Frahaan Hussain

Video

C++ Development - The Complete Coding Guide

77 Lectures 5.5 hours

Frahaan Hussain

Video

Tic-Tac-Toe Clone - The Complete Cocos2d-x C++ Game Course

12 Lectures 3.5 hours

Frahaan Hussain

Advertisements