What is the `this` pointer in C++?
If we’re learning C++, we’ll encounter a lot of object-oriented programming concepts. One concept that often puzzles beginners is how member functions know which specific object they’re working with. When we create multiple objects of the same class, how does a member function distinguish between them?
The answer lies in the this
pointer. Think of the this
pointer like a name tag that every object wears when calling its own methods. Just as a name tag helps identify who’s speaking in a group conversation, the this
pointer helps member functions identify which specific object they’re working with.
Let’s explore exactly how this mechanism works and why it’s so important for effective C++ programming.
What is the this
pointer in C++?
The this
pointer is an implicit pointer available in all non-static member functions of a class. It holds the memory address of the object that invoked the member function. When we call a member function on an object, the compiler automatically passes the address of that object as a hidden parameter called this
.
To understand why the this
pointer is necessary, we need to understand how objects and member functions work together:
1. Each object gets its own copy of data members: When we create multiple objects of a class, each object has its own separate copy of the class’s data members.
2. All objects share the same member functions: Unlike data members, there’s only one copy of each member function that all objects of the class share.
Since multiple objects share the same member function code, the this
pointer tells the function which object’s data to work with.
Learn TypeScript: Object Types
Learn how to define property names, represent complex object shapes, and write more organized code in TypeScript.Try it for freeSyntax of this
pointer
this
The this
keyword is a prvalue expression whose value is the address of the current object.
Usage patterns
// Accessing member variablesthis->memberVariable// Calling member functionsthis->memberFunction()// Returning reference to current objectreturn *this;// Comparing with another objectreturn this == &other;
Type information
The type of the this
pointer varies based on the member function’s qualifiers:
For a class Student: The type of
this
isStudent*
(pointer to Student)For const member functions: The type of
this
isconst Student*
(pointer to const Student)For volatile member functions: The type of
this
isvolatile Student*
(pointer to volatile Student)
Here’s an example that demonstrates how the type of this
changes based on function qualifiers:
class Student {private:int age;std::string name;double gpa;public:void regularFunction() {// this is of type: Student* constthis->age = 20; // Can modify private membersthis->name = "John"; // Can modify private membersthis->gpa = 3.5; // Can modify private members}void constFunction() const {// this is of type: const Student* const// this->age = 25; // ERROR: Cannot modify in const functionint currentAge = this->age; // Can read private membersstd::string currentName = this->name; // Can read private membersstd::cout << "Age: " << this->age << std::endl; // Can access for reading}};
The this
pointer itself is always a constant pointer—we cannot change what it points to, but we may be able to modify the object it points to depending on the function’s const
qualification.
With the syntax covered, let’s explore practical scenarios where the this
pointer becomes essential for solving real programming challenges.
Implementation of this
pointer in C++
Example 1 - Resolving parameter and member name conflicts
When parameter names match member variable names, the compiler cannot distinguish between them without the this
pointer.
#include <iostream>using namespace std;class BankAccount {private:double accountBalance;public:void setAccountBalance(double newBalance) {// Without 'this', both accountBalance refer to the parameter// accountBalance = accountBalance; // This won't work as expected// Using 'this' to access the member variablethis->accountBalance = newBalance;}void displayBalance() {cout << "Account Balance = $" << accountBalance << endl;}};int main() {BankAccount customerAccount;customerAccount.setAccountBalance(1500.75);customerAccount.displayBalance();return 0;}
Output:
Account Balance = $1500.75
In the setAccountBalance()
function, when a parameter has the same name as a member variable, the parameter takes precedence in the local scope. Without this->
, writing accountBalance = accountBalance
would assign the parameter to itself, leaving the member variable unchanged. Using this->accountBalance
explicitly refers to the member variable, allowing us to assign the parameter value to it correctly.
Example 2- Enabling method chaining
Method chaining allows multiple method calls on the same object in a single statement by returning *this
.
#include <iostream>using namespace std;class Rectangle {private:int width, height;public:Rectangle(int initialWidth = 0, int initialHeight = 0) {this->width = initialWidth;this->height = initialHeight;}Rectangle& setWidth(int newWidth) {width = newWidth;return *this; // Return reference to current object}Rectangle& setHeight(int newHeight) {height = newHeight;return *this; // Return reference to current object}void displayDimensions() {cout << "Width = " << width << " Height = " << height << endl;}};int main() {Rectangle rect(5, 5);// Method chaining - all calls modify the same objectrect.setWidth(10).setHeight(20);rect.displayDimensions();return 0;}
Output:
Width = 10 Height = 20
Each method (setwidth()
and setheight()
) returns *this
, which is a reference to the current object. This allows the next method to be called on the same object directly. When we write rect.setwidth(10).setheight(20)
, first setwidth(10)
is called and returns a reference to rect
, then setheight(20)
is called on that same object.
Now that we’ve seen the this
pointer in action through various implementations, let’s examine its fundamental characteristics that define how it behaves in different contexts.
Characteristics of this
pointer in C++
The this
pointer has several key characteristics that define its behavior in C++:
Implicit parameter: The
this
pointer is automatically 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.Constant pointer: The
this
pointer is a constant pointer (cannot be modified), meaning we cannot change which object it points to.Type depends on function qualifiers: For a class X, the type of
this
isX*
. If a member function is declared asconst
, then the type ofthis
isconst X*
. For volatile functions, the type isvolatile X*
.Points to object’s memory location: The
this
pointer holds the actual memory address of the current object, allowing direct access to the object’s location.Can be dereferenced: Since
this
is a pointer, it can be dereferenced using*this
to access the current object, which is commonly used when returning the object from member functions.
Why friend functions don’t use the this
pointer?
Before exploring the limitations of the this
pointer, it’s important to understand why certain functions don’t have access to it. Friend functions cannot use the this
pointer, which helps clarify the nature of this
itself.
Friend functions are not member functions of a class—they are external functions that have been granted special access to a class’s private and protected members. Since they exist outside the class and are not called on specific object instances, they don’t receive the automatic this
pointer that member functions get.
Member Functions vs Friend Functions
Member functions are called on an object using dot notation (object.memberFunction()
) or arrow notation (pointer->memberFunction()
). The compiler automatically passes the object’s address as the this
pointer.
Friend functions are called with objects as explicit parameters (friendFunction(object)
). They receive objects as regular parameters, not through an implicit this
pointer.
Limitations of this
pointer
The this
pointer has certain limitations and potential pitfalls that developers should keep in mind:
Not available in static member functions: Static functions are tied to the class itself, not to any specific object, so they don’t have access to the
this
pointer.Cannot be modified: The
this
pointer is a constant pointer, meaning we cannot change which object it points to.Undefined behavior after object destruction: Using
this
after an object is destroyed or while it’s being destroyed can cause undefined behavior, especially dangerous withdelete this
.Multiple inheritance complexities: In multiple inheritance scenarios, conflicts can occur if different base classes share members with identical names, making it unclear which member the
this
pointer is pointing to.Potential for dangling references: Returning
*this
from a temporary object can leave behind a dangling reference, which could cause unexpected behavior.Name shadowing confusion: While
this
helps differentiate between member variables and local variables, it can still lead to confusion if not used carefully.
Conclusion
The this
pointer is a fundamental mechanism in C++ that enables object-oriented programming by allowing member functions to identify which specific object they’re operating on. It automatically provides each object with a reference to itself, solving the critical problem of how shared member functions work with different object instances.
Mastering the this
pointer is essential for writing robust, maintainable C++ code and implementing effective object-oriented designs.
Frequently asked questions
1. What is ->
called in C++?
The ->
operator is the “arrow operator” used to access members of an object through a pointer. ptr->member
is equivalent to (*ptr).member
. With the this
pointer, we use this->member
to access the current object’s members.
2. Why do we use ::
in C++?
The ::
operator is the “scope resolution operator” used to specify which scope an identifier belongs to. We use it to access global variables (::variable
), define member functions outside classes (ClassName::functionName
), and access static members (ClassName::staticMember
).
3. What is a pointer in C++?
A pointer is a variable that stores the memory address of another variable. Pointers enable dynamic memory allocation, efficient handling of large objects, and polymorphism. The this
pointer is a special automatic pointer that always points to the current object in member functions.
4. When to use pointers?
Use pointers for dynamic memory allocation, avoiding expensive copying of large objects, implementing data structures like linked lists, optional parameters (using nullptr
), and achieving polymorphism with base class pointers. Prefer references when you don’t need pointer-specific features.
5. What are smart pointers in C++?
Smart pointers are objects that behave like pointers but provide automatic memory management. C++11 introduced std::unique_ptr
(exclusive ownership), std::shared_ptr
(shared ownership), and std::weak_ptr
(non-owning observation). They automatically delete managed objects when no longer needed, preventing memory leaks.
'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'
Meet the full teamRelated articles
- Article
Memory Allocation
What is memory allocation? And what is manual memory management? - Article
The Two-Pointer Technique in a Linked List
Learn about how the most common singly linked list problems can be solved by iterating with two-pointers. - Article
Doubly Linked Lists
A conceptual overview of Doubly Linked Lists.
Learn more on Codecademy
- Free course
Learn TypeScript: Object Types
Learn how to define property names, represent complex object shapes, and write more organized code in TypeScript.Beginner Friendly1 hour - Free course
Learn C#: References
Unlock the power of references, an essential aspect of object-oriented programming in C#.Beginner Friendly3 hours - Free course
Learn C++: Functions
Take your C++ skills to the next level by learning how to use using C++ functions to write more flexible, modular, reusable code.Beginner Friendly3 hours