This Pointer in C++

This Pointer in C++

6 mins read2K Views Comment
clickHere
Updated on Feb 23, 2023 18:11 IST

In C++, the “this” pointer holds the memory address of the class instance that is being called by a member function, allowing those functions to correctly access the object’s data members.

2023_02_MicrosoftTeams-image-308.jpg

It’s not necessary to explicitly define the “this” pointer as a function argument within the class, as the compiler handles it automatically. In this tutorial, we will discuss the use of this pointer in C++ with the aid of suitable examples.

We will be covering the following sections: 

Introduction to this Pointer in C++ 

C++ enables the creation of custom data types through the use of classes. These classes contain member variables and associated member functions. In C++, it’s possible to create multiple objects of the same class, each of which has its own copy of the class’s data members. However, all class objects use the same function definitions as defined in the code segment. 

You can also explore: Increasing Precision With Setprecision in C++

Since all objects of a class can only access a common member function, there can be confusion as to which data member should be updated or accessed. To address this issue, the compiler employs a specific kind of pointer, known as the “this” pointer. The this pointer in C++ holds the memory address of the class instance (i.e., object) that is being called from the member function, allowing those functions to access the correct data members of that specific object. 

Using this Pointer in C++ 

In C++, the “this” pointer is a special keyword that can be used inside a member function of a class to refer to the object that called the function. The “this” pointer is a pointer to the object itself, and is used to access the object’s data members and member functions. 

Here are some common uses in C++: 

Accessing data members: Inside a member function, you can use the “this” pointer to access the data members of the object that called the function.

For example: 

 
class MyClass {
private:
int value;
public:
void setValue(int value) {
this->value = value;
}
};
Copy code

In this example, the “this” pointer is used to access the “value” data member of the object. 

You can also explore: Check Palindrome in C++

Returning the object itself: Inside a member function, you can use the “this” pointer to return a reference to the object that called the function. This can be useful for chaining multiple member function calls together.

For example: 

 
class MyClass {
public:
MyClass& doSomething() {
// do something...
return *this; // return a reference to the object itself
}
};
Copy code

In this example, the “doSomething” member function returns a reference to the object itself by dereferencing the “this” pointer and returning it. 

Comparing objects: Inside a member function, you can use the “this” pointer to compare the object that called the function to another object.

For example: 

 
class MyClass {
public:
bool isSameAs(const MyClass& other) {
return this == &other; // compare the object to "other"
}
};
Copy code

In this example, the “isSameAs” member function compares the object that called the function to another object by comparing their addresses using the “this” pointer and the address-of operator “&”. 

You can also explore: Printing Character’s ASCII Value in C++ Program

Example  

Let’s say we create an object called objectA from the class A. A has a non-static member function called foo(). When we call foo() using the syntax objectA.foo(), the this pointer is implicitly passed to the function by the compiler. The this pointer can be used inside the function body to access the data members of objectA, since it holds the memory address of objectA

In other words, calling foo() is equivalent to calling foo(&objectA), since C++ adds a new parameter to the function. This new parameter is consistently named this and is a hidden pointer that points to the class object inside every class method or function. As a result, C++ internally converts the function definition from  

void A::foo();  

to 

void A::foo(A* const this); 

Let’s look at the following example: 

 
#include <iostream>
class MyClass {
private:
int value;
public:
void setValue(int value) {
this->value = value; // accessing class member using "this" pointer
}
void printValue() {
std::cout << "Value: " << this->value << std::endl; // accessing class member using "this" pointer
}
};
int main() {
MyClass obj;
obj.setValue(42);
obj.printValue();
return 0;
}
Copy code

Output: 

2023_02_image-150.jpg

In this example, we define a class called MyClass with a private member variable called “value”. The class also has two member functions, setValue() and printValue(). The setValue() function sets the value of the private member variable to a given value, while the printValue() function prints the value of the private member variable to the console. 

Note that inside the setValue() and printValue() functions, we use the “this” pointer to access the class member variable “value”. By using “this->value”, we can differentiate between the class member variable and any local variable with the same name, and ensure that we’re updating or accessing the correct variable. 

When we create an object of MyClass and call its member functions, the “this” pointer will point to that particular object, allowing the member functions to access the object’s data members. 

You can also explore: SetPrecision in C++ With Examples

this Pointer as a Constructor 

In C++, the “this” pointer can also be used as a constructor, a special member function that is called when an object of the class is created. When used as a constructor, the “this” pointer is used to refer to the object that is being created. 

Here is an example of how to use it as a constructor: 

 
class MyClass {
private:
int value;
public:
MyClass(int value) {
this->value = value;
}
};
Copy code

In this example, the “MyClass” constructor takes an integer parameter “value” and sets the value of the “value” data member to the passed value. The “this” pointer is used to refer to the object that is being created and set its data member. 

When an object of the class is created, the constructor is called automatically, and the “this” pointer points to the new object. For example: 

MyClass myObject(42); // create a new object of MyClass with value 42 

In this example, the “MyClass” constructor is called with the value 42, and the “this” pointer points to the new object. The “value” data member of the object is set to 42. 

Using the “this” pointer as a constructor can be useful for initializing data members of a class object when it is created. 

You must explore: What are Getline Function in C++?

Deleting this Pointer 

It is not recommended to delete the “this” pointer in C++. The “this” pointer points to the object that is currently executing a member function, and deleting it would cause undefined behavior and likely result in a program crash. 

The “this” pointer is an implicit pointer and is managed by the C++ compiler. The compiler automatically generates the code to pass the “this” pointer as a hidden argument to member functions, and manages the lifetime of the object that the “this” pointer points to. 

Therefore, it is not necessary to delete the “this” pointer in C++. In fact, attempting to delete the “this” pointer is a common mistake and a potential source of bugs in C++ programs. 

To avoid any issues related to the “this” pointer, it is best to simply let the C++ compiler handle it and focus on writing correct and well-designed code that does not rely on manually managing the “this” pointer. 

You can also explore: All About Virtual Functions in C++

Endnotes 

In conclusion, the “this” pointer is an essential feature of C++ that enables member functions to access the correct data members of an object. The “this” pointer is a hidden pointer that points to the object that is executing a member function. It is automatically passed as an implicit argument to member functions by the C++ compiler. 

Hope this article was useful to you. Explore our C++ articles to find out more about the language and consolidate your knowledge of the fundamentals.   

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio

Comments