In the Classes & Objects topic, we wrote acc1.deposit(5000) and acc2.deposit(800), and each call changed the right account. But there is only one copy of deposit() in the program, shared by all objects. So how does that single function know whose balance to change?
The answer is a hidden pointer that the compiler passes to every member function: this. In this topic we'll see what this really is, its type, and the four everyday jobs it does: resolving name clashes, method chaining with *this, checking for self-assignment, and handing the current object to other code. We'll finish with the C++23 alternative, the explicit object parameter.
What Is the this Pointer?
Inside a non-static member function, the keyword
thisis a pointer whose value is the address of the object on which the function was called.
When you call a.whoAmI(), this points to a. When you call b.whoAmI(), this points to b. Let's check by printing the addresses:
#include <iostream>
class Box
{
private:
int id;
public:
explicit Box(int i) : id(i) {}
void whoAmI() const
{
std::cout << "Box " << id << ": this = " << this << '\n';
}
};
int main()
{
Box a(1);
Box b(2);
std::cout << "&a = " << &a << '\n';
a.whoAmI();
std::cout << "&b = " << &b << '\n';
b.whoAmI();
Box* p = &b;
p->whoAmI(); // through a pointer: this is still &b
return 0;
}
Sample output (the actual addresses change from run to run):
&a = 0x7ffc6a269878
Box 1: this = 0x7ffc6a269878
&b = 0x7ffc6a26987c
Box 2: this = 0x7ffc6a26987c
Box 2: this = 0x7ffc6a26987c
Inside whoAmI(), this always equals the address of the object we called it on, whether we used a., b. or p->. (In this run the two objects happen to sit 4 bytes apart, the size of one Box holding a single int. Where local objects are placed on the stack is up to the compiler, so the gap or even the order may differ on your machine.)
How the Compiler Uses this
Conceptually, the compiler turns every member function into an ordinary function with one extra, hidden first parameter, and turns every call into a call that passes the object's address:
What we write What the compiler conceptually does
──────────────────────────────── ─────────────────────────────────────────
void Box::whoAmI() const void Box_whoAmI(const Box* this)
{ {
std::cout << id; std::cout << this->id;
} }
a.whoAmI(); Box_whoAmI(&a);
p->whoAmI(); Box_whoAmI(p);
Two consequences:
Whenever you write a member's name, like
id, inside a member function, the compiler reads it asthis->id. Writingthis->idyourself is allowed but usually unnecessary.This is why member functions don't take space inside objects (as we saw with
sizeofin Classes & Objects): the code is shared, and only the data differs, reached throughthis.
(Exactly how this is passed, usually in a CPU register, is up to the compiler. The translation above is a mental model, not real code.)
The Type of this
this is not a variable. It is a keyword whose value is a pointer, and you can't change it:
void Point::reset()
{
this = nullptr; // error: this cannot be changed
}
error: lvalue required as left operand of assignment
Its type depends on the kind of member function:
Inside ... of class X | Type of this | Meaning |
|---|---|---|
| A normal member function | X* | Can read and modify the object |
A const member function | const X* | Can only read the object |
| A constructor or destructor | X* | Points to the object being built / destroyed |
A static member function | No this at all | Not called on an object |
We'll come back to the const and static rows shortly.
Use 1: Resolving Name Conflicts
It's natural to give a parameter the same name as the member it sets. But inside the function, the parameter hides the member: a plain name refers to the nearest declaration, which is the parameter. this->name says explicitly "the member of the current object".
#include <iostream>
#include <string>
class Student
{
private:
std::string name;
int age = 0;
public:
// parameter names deliberately the same as the members
void setWrong(std::string name, int age)
{
name = name; // assigns the parameter to itself!
age = age; // the member is never touched
}
void setRight(const std::string& name, int age)
{
this->name = name; // member = parameter
this->age = age;
}
void show() const
{
std::cout << "name = \"" << name << "\", age = " << age << '\n';
}
};
int main()
{
Student s;
s.setWrong("Asha", 20);
s.show();
s.setRight("Asha", 20);
s.show();
return 0;
}
Output:
name = "", age = 0
name = "Asha", age = 20
In setWrong(), both sides of name = name; are the parameter, so the member stays empty and age stays 0. The program compiles without a single warning under -Wall -Wextra, which is what makes this bug dangerous. (Adding -Wshadow makes GCC warn about parameters that shadow members.)
Three common ways to avoid the problem:
| Approach | Example |
|---|---|
Use this-> | this->name = name; |
| Use a member initializer list in constructors (the member name outside the parentheses can only mean the member) | Student(std::string name) : name(name) {} |
| Use a naming convention for members | name_, m_name, or a different parameter name |
In the initializer list form name(name), the first name must be a member (that's what the list initializes), while the name inside the parentheses follows normal lookup and finds the parameter. So it works correctly without this.
Use 2: Returning *this for Method Chaining
this is a pointer, so *this is the object itself. A member function that returns *this by reference lets the caller immediately call another member function on the same object. This is called method chaining (or a fluent interface).
#include <iostream>
#include <string>
class Pizza
{
private:
std::string size = "medium";
std::string toppings;
int cheese = 1;
public:
Pizza& setSize(const std::string& s)
{
size = s;
return *this; // return the current object itself
}
Pizza& addTopping(const std::string& t)
{
if (!toppings.empty())
toppings += ", ";
toppings += t;
return *this;
}
Pizza& extraCheese()
{
cheese++;
return *this;
}
void show() const
{
std::cout << size << " pizza with " << toppings
<< " (cheese x" << cheese << ")\n";
}
};
int main()
{
Pizza order;
order.setSize("large")
.addTopping("onion")
.addTopping("capsicum")
.extraCheese()
.extraCheese(); // every call works on the same object
order.show();
return 0;
}
Output:
large pizza with onion, capsicum (cheese x3)
Step by step: order.setSize("large") modifies order and returns a reference to order; .addTopping("onion") is called on that reference, i.e. on order again, and so on. extraCheese() runs twice, so the cheese count goes from 1 to 3.
You have used this pattern since your first program: std::cout << a << b works because << returns a reference to the same stream (we will write such operators ourselves in Operator Overloading).
Return by Reference, Not by Value
The return type matters a lot. Watch what happens if we return *this by value:
#include <iostream>
class Counter
{
private:
int value = 0;
public:
Counter& incRef() { value++; return *this; } // returns the object itself
Counter incCopy() { value++; return *this; } // returns a COPY of the object
int get() const { return value; }
};
int main()
{
Counter a;
a.incRef().incRef().incRef();
std::cout << "by reference: " << a.get() << '\n';
Counter b;
b.incCopy().incCopy().incCopy(); // only the first call changes b
std::cout << "by value: " << b.get() << '\n';
return 0;
}
Output:
by reference: 3
by value: 1
incCopy() returns a copy of the object (using the copy constructor from Constructors & Destructors). The first call increments b, but the second call runs on that temporary copy, and the third on another copy. Those copies are destroyed at the end of the statement, so b was incremented only once.
| Expression | Type (in a non-const member of X) | What it is |
|---|---|---|
this | X* | Address of the current object |
*this | an lvalue of type X | The current object itself |
return type X& with return *this; | Caller gets the same object: chaining works | |
return type X with return *this; | Caller gets a copy: later calls change the copy |
Use 3: Checking for Self-Assignment
In Constructors & Destructors, we wrote a copy assignment operator for IntArray ending with return *this;. Now we can understand that line, and add another common use of this: detecting a = a; by comparing addresses.
#include <iostream>
#include <algorithm> // std::copy
class IntArray
{
private:
int* data;
int size;
public:
explicit IntArray(int n) : data(new int[n]{}), size(n) {}
~IntArray() { delete[] data; }
IntArray(const IntArray& other) : data(new int[other.size]), size(other.size)
{
std::copy(other.data, other.data + size, data);
}
IntArray& operator=(const IntArray& other)
{
if (this == &other) // assigning an object to itself?
{
std::cout << " self-assignment: nothing to do\n";
return *this;
}
std::cout << " copying " << other.size << " elements\n";
int* fresh = new int[other.size];
std::copy(other.data, other.data + other.size, fresh);
delete[] data;
data = fresh;
size = other.size;
return *this;
}
void set(int i, int v) { data[i] = v; }
int get(int i) const { return data[i]; }
};
int main()
{
IntArray a(3), b(3), c(3);
a.set(0, 42);
std::cout << "a = a;\n";
a = a;
std::cout << "c = b = a;\n";
c = b = a; // right to left: b = a, then c = b
std::cout << "a[0] = " << a.get(0) << ", b[0] = " << b.get(0)
<< ", c[0] = " << c.get(0) << '\n';
return 0;
}
Output:
a = a;
self-assignment: nothing to do
c = b = a;
copying 3 elements
copying 3 elements
a[0] = 42, b[0] = 42, c[0] = 42
if (this == &other)compares addresses, not contents. It is true only when both sides are literally the same object. Self-assignment rarely appears as plaina = a;; it usually sneaks in through references or pointers, such asarr[i] = arr[j];wheni == j.Without the check, an operator that deletes first and copies afterwards would read from memory it just freed (use-after-free). Our version copies before deleting, so it is safe either way; the check just avoids pointless work.
Returning
*thisby reference is what makesc = b = a;work. Assignment groups right to left:b = aruns first and returnsb, which is then assigned toc. That's why "copying 3 elements" appears twice.
Use 4: Passing the Current Object to Other Code
Sometimes an object needs to give itself to another object or function, for example to register itself or to let others link back to it. this is exactly that address.
#include <iostream>
#include <string>
class Team; // forward declaration
class Player
{
private:
std::string name;
Team* team = nullptr; // which team this player belongs to
public:
explicit Player(const std::string& n) : name(n) {}
void joinTeam(Team* t) { team = t; }
const std::string& getName() const { return name; }
void introduce() const; // defined after Team is complete
};
class Team
{
private:
std::string name;
Player* members[5] = {};
int count = 0;
public:
explicit Team(const std::string& n) : name(n) {}
void add(Player& p)
{
members[count++] = &p;
p.joinTeam(this); // pass the current Team object to the player
}
const std::string& getName() const { return name; }
};
void Player::introduce() const
{
std::cout << "I am " << name << " of team " << team->getName() << '\n';
}
int main()
{
Team india("Blue Tigers");
Player p1("Rohit"), p2("Smriti");
india.add(p1);
india.add(p2);
p1.introduce();
p2.introduce();
return 0;
}
Output:
I am Rohit of team Blue Tigers
I am Smriti of team Blue Tigers
Inside Team::add(), p.joinTeam(this) passes the address of the Team object on which add() was called (here india). Each player stores it and later uses it to print the team's name. Writing p.joinTeam(*this) would pass the object itself, which would suit a function taking Team&.
Careful: a stored
thispointer is only valid while that object is alive and stays at the same address. If theTeamwere destroyed while the players still existed, everyteampointer would dangle (see Dynamic Memory Allocation). And a copy of the team would not update the players: they would still point to the original.
this in const Member Functions
In Classes & Objects, calling a non-const function on a const object gave this strange error: passing 'const Counter' as 'this' argument discards qualifiers. Now it makes sense:
For a
constobject,&objhas typeconst Counter*.A non-const member function expects
thisof typeCounter*.Converting
const Counter*toCounter*would "discard" theconstqualifier, which C++ never does implicitly. Hence the error.
The const written after a member function's parameter list is really a const on this. Inside such a function, this is const X*, so every member is read-only, unless it is declared mutable.
#include <iostream>
class Sensor
{
private:
int reading = 0;
mutable int timesRead = 0; // may change even in const functions
public:
void update(int r) { reading = r; } // here: this is Sensor*
int read() const // here: this is const Sensor*
{
timesRead++; // OK: mutable
// reading = 0; // error: assignment of member in read-only object
return reading;
}
int getTimesRead() const { return timesRead; }
};
int main()
{
Sensor s;
s.update(37);
const Sensor& view = s; // read-only access
std::cout << view.read() << ' ' << view.read() << '\n';
std::cout << "read " << view.getTimesRead() << " times\n";
// view.update(40); // error: update() is not const
return 0;
}
Output:
37 37
read 2 times
If we uncomment reading = 0; inside read(), g++ reports:
error: assignment of member 'Sensor::reading' in read-only object
"Read-only object" means *this, seen through a const Sensor*. The mutable member timesRead is the exception: it can change even inside a const function. Use mutable only for internal bookkeeping (counters, caches) that doesn't change the object's observable value.
Static Member Functions Have No this
A static member function belongs to the class as a whole and is not called on any object, so there is no object for this to point to. We'll study static members properly in the next topic, Static Members; for now, just remember the rule:
class Counter
{
static int total;
public:
static int getTotal() { return this->total; } // error
};
error: 'this' is unavailable for static member functions
C++23: The Explicit Object Parameter ("Deducing this")
C++23 adds a second way to write a member function: instead of the hidden this pointer, you declare the object as an explicit first parameter, marked with the keyword this. The parameter is usually named self.
#include <iostream>
class Point
{
private:
int x, y;
public:
Point(int x, int y) : x(x), y(y) {} // member(parameter): no this-> needed
// C++23 explicit object parameter: "self" plays the role of *this
void print(this const Point& self)
{
std::cout << "(" << self.x << ", " << self.y << ")\n";
}
// the classic form, for comparison
void printClassic() const
{
std::cout << "(" << this->x << ", " << this->y << ")\n";
}
};
int main()
{
Point p(3, 4);
p.print(); // called exactly like a normal member function
p.printClassic();
return 0;
}
Output:
(3, 4)
(3, 4)
void print(this const Point& self)is called exactly like before:p.print(). The objectpis passed asself.Inside such a function there is no
this; you must writeself.x, notx.this const Point&plays the role of a trailingconst. Its real power appears with templates (one function that works for const and non-const objects alike) and recursive lambdas, which are topics for later (Templates, Lambda Expressions).It needs a C++23 compiler, for example GCC 14 or later with
-std=c++23. Most code you read will still use the classicthispointer, so learn that first.
Notice also the constructor Point(int x, int y) : x(x), y(y) {}, which uses the initializer-list trick from Use 1.
Two Dangerous Corners
Calling a Member Function Through a Null Pointer
Box* p = nullptr;
p->whoAmI(); // undefined behavior
This is undefined behavior even if the function never touches a data member. It may appear to "work" and print this = 0, or crash, or the optimizer may assume p can't be null and remove your later null checks. Never write if (this == nullptr) checks inside member functions; check the pointer before calling.
delete this
A member function may execute delete this;, and it is legal, but only if all of these hold: the object was created with plain new (not new[], not on the stack, not a global), nothing touches any member or calls a member function after the delete, and nobody uses other pointers to the object afterwards. It appears in a few low-level designs (such as reference-counted objects), but in normal code smart pointers do this job far more safely (see Smart Pointers).
Common Mistakes
Writing
x = x;when the parameter has the same name as the member. Usethis->x = x;or an initializer list.Returning
*thisby value from a function meant for chaining. ReturnX&.Forgetting
return *this;in a copy assignment operator. The function has a return type ofX&, so flowing off the end is undefined behavior (GCC warns with-Wreturn-type, which is on by default for C++).Comparing contents instead of addresses in a self-assignment check:
if (*this == other)is a different question (and needsoperator==). Usethis == &other.Using
thisin a static member function. There isn't one.Storing
thissomewhere and using it after the object has been destroyed.Using
this.x(Java style). In C++,thisis a pointer: writethis->xor(*this).x.
Interview / GATE Questions
1. What is the type of this inside a const member function of class X?
const X*. In a non-const member function it is X*. In both cases this itself can't be assigned to, because it is a prvalue (a pure value), not a variable.
2. Can a static member function use this? Why?
No. A static member function is not called on an object, so there is no object address to pass. Using this inside it is a compile error. Static functions can still access static data members directly.
3. What does this print? class A { int x = 0; public: void set(int x) { x = x; } int get() const { return x; } }; followed by A a; a.set(5); std::cout << a.get();
0. Inside set(), both xs refer to the parameter, so the member is never changed. The fix is this->x = x;.
4. Why does a copy assignment operator usually return *this by reference?
To allow chained assignment like a = b = c; (which works like built-in types) without making an unnecessary copy. Returning X& gives the caller the assigned object itself.
5. A member function Counter inc() { ++n; return *this; } is called as c.inc().inc().inc(); on a fresh c with n == 0. What is c.n afterwards?
1. Only the first call runs on c; it returns a copy, and the next two calls modify temporary copies. With the return type Counter&, the answer would be 3.
6. Is delete this; allowed in C++?
Yes, provided the object was allocated with plain new and no member is accessed (and no other pointer to the object is used) after the deletion. Otherwise it is undefined behavior. It is rarely needed in modern code.
Summary
thisis a pointer to the object on which a non-static member function was called. The compiler passes it implicitly, and member names inside the function meanthis->member.Its type is
X*in normal member functions andconst X*inconstones; static member functions have nothis.Use
this->memberwhen a parameter hides a member (or use the initializer listmember(member)).Return
*thisby reference for method chaining and from assignment operators.this == &otherdetects self-assignment.thiscan be passed to other functions, but a stored copy dangles once the object dies.C++23's explicit object parameter (
this const X& self) is an alternative to the implicitthis.Calling a member function through a null pointer is undefined behavior;
delete thisis legal only under strict conditions.