Appearance
The this Keyword
this is a pointer that points to the current object — the object that called the member function.
Think: When you say "I am doing this" — "I" refers to yourself. Similarly,
thisrefers to the current object inside a class.
Basic Example
cpp
class Car {
public:
string brand;
void setBrand(string brand) {
this->brand = brand; // this->brand = object's brand
// brand alone = parameter
}
};Without this->, the compiler gets confused between the parameter and the member variable when both have the same name.
5 Main Uses of this
1. Resolve Name Conflict (most common)
cpp
class Student {
string name; int age;
public:
Student(string name, int age) {
this->name = name; // member variable
this->age = age; // parameter age
}
};2. Return Current Object — Method Chaining
cpp
class Counter {
int count = 0;
public:
Counter& increment() { count++; return *this; }
Counter& decrement() { count--; return *this; }
void show() { cout << "Count: " << count << endl; }
};
int main() {
Counter c;
c.increment().increment().increment().decrement();
c.show(); // Count: 2
}3. Pass Current Object to Another Function
cpp
void start() { process(this); } // passing current object4. Compare with Another Object
cpp
bool isBigger(Box& other) {
return this->volume > other.volume;
}5. Delete Current Object
cpp
void destroy() { delete this; } // use carefully!this Is a Pointer — Correct Syntax
cpp
cout << this << endl; // prints address of current object
cout << this->x << endl; // correct — access via ->
cout << (*this).x << endl; // also correctthis Is NOT Available in Static Methods
cpp
static void show() {
cout << this->x << endl; // ERROR! static has no 'this'
}Key Points
| Point | Detail |
|---|---|
| Type | Pointer (ClassName*) |
| Available in | All non-static member functions |
| Not available in | Static methods |
| Main use | Resolve name conflict, method chaining |
| Access members | this->member |
One-liner: "this is an implicit pointer available in all non-static member functions that points to the current object invoking the function."