Topic 61 of 83
The this Pointer
Overview
Every non-static member function has a hidden pointer named `this` that points to the object currently calling the function. It's useful for returning the object itself or resolving naming conflicts.
Syntax
cpp
class Player {
int health;
public:
void setHealth(int health) {
// 'this->health' is the class member, 'health' is the parameter
this->health = health;
}
// Returning reference to current object for method chaining
Player& heal() {
this->health += 10;
return *this; // Dereference pointer to return object
}
};Common Pitfalls
- Returning `this` (a pointer) when the function signature expects a reference (you must return `*this`).
Interview Tips
- Static member functions do NOT have a `this` pointer because they belong to the class itself, not to any specific object instance.
Real-World Example
Method chaining using `return *this`.
example
cpp
#include <iostream>
using namespace std;
class Text {
string str = "";
public:
Text& append(string s) {
str += s;
return *this;
}
void print() { cout << str << endl; }
};
int main() {
Text t;
// Chaining methods!
t.append("Hello ").append("World").append("!");
t.print();
return 0;
}