Table of Contents
Back Button
Back to Chapter
C++ Setting Up
C++ Introduction
No items found.
C++ Basics
No items found.
C++ Control Statements
No items found.
C++ Logical Operators
No items found.
C++ Procedural Programming
No items found.
C++ Structural Programming
No items found.
C++ Implementation of OOPS
No items found.
C++ Arrays and Vectors
No items found.
C++ Error Handling
No items found.
C++ File Handling
No items found.

C++ this pointer

To understand ‘this’ pointer, it is necessary to know how objects look at functions and data members of a class.

  • Each object gets its own copy of the data member.
  • All-access the same function definition as present in the code segment.

This means each object of a class has a its own separate copies of data members but share the same member functions.

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/3f6c1c41-30c1-41cb-b94e-1af00432349a/Untitled_Diagram_(36).png

If there is only one copy of each member function and is used by multiple objects, how are the proper data members are accessed and updated?

The compiler provides an implicit pointer along with the names of the functions as ‘this’.

The ‘this’ pointer is passed as a hidden argument to all non-static member function calls and is available as a local variable within the body of all non-static functions.

a non-static method is one that is called ON an instance of some class, whereas a static method belongs to the class itself.

‘this’ pointer is not available in static member functions as static member functions can be called without any object

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 this pointer, because friends are not members of a class. Only member functions have this pointer.

Let us try understanding this concept with the help of an example

#include 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" <
Output: Constructor called. Constructor called. Box2 is equal to or larger than Box1
Ask queries
Contact Us on Whatsapp
Hi, How Can We Help You?