this Pointer

Self-reference in member functions

Interview Relevant: Object identity

this Pointer

Implicit pointer to the current object.

Code Examples

Using this pointer for self-reference.

cpp
1class Counter {
2    int value;
3
4public:
5    Counter(int value) {
6        this->value = value;  // Disambiguate
7    }
8
9    // Return *this for method chaining
10    Counter& increment() {
11        value++;
12        return *this;
13    }
14
15    Counter& add(int n) {
16        value += n;
17        return *this;
18    }
19
20    void print() const {
21        cout << value << endl;
22    }
23};
24
25Counter c(0);
26c.increment().add(5).increment().print();  // 7
27
28// this in lambda capture
29class Example {
30    int x = 10;
31    void method() {
32        auto lambda = [this]() {
33            return x;  // Access member via this
34        };
35    }
36};

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In