CodeBlanks Logo Icon CodeBlanks

The this pointer

Learn to access the class itself with the this pointer.

The this pointer

Inside a member function, this is a pointer to the object the function was called on. Writing this->name accesses the object's own member explicitly. This disambiguates when a parameter name matches a member name.

Example: void setName(std::string name) { this->name = name; }. The right-hand name is the parameter; the left-hand this->name is the object's member. Without this, name = name; assigns the parameter to itself; the member does not change.

Chaining calls

A common use of this is method chaining. If a member function returns return *this;, calls can be chained one after another.

Example: Builder& add(int x) { total += x; return *this; }. Usage: builder.add(1).add(2);. Each add returns the same object, so the next call works on the same object. *this is the object the pointer points to.

Practice Write the setName member with this

Define a Player class. Under public: add std::string name; and the member function void setName(std::string name) { this->name = name; }. In main create an instance, call setName("Alex") and print name with std::cout.

Starter code

main.cpp
#include <iostream>
#include <string>

// Define the Player class here

int main() {
    // Create a Player instance, call setName and print name
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <string>

class Player {
public:
    std::string name;
    void setName(std::string name) {
        this->name = name;
    }
};

int main() {
    Player player;
    player.setName("Alex");
    std::cout << player.name;
    return 0;
}

Expected output

Alex

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does this->name = name; do?

main.cpp
void setName(std::string name) { this->name = name; }
  • Creates a new local variable
  • Deletes the parameter
  • Updates the object's member with the parameter value Correct answer
  • Does nothing

Explanation: this->name is the member, the right-hand name is the parameter.

2 Write the this pointer

Question
void setName(std::string name) { ____->name = name; }
Answer
void setName(std::string name) { this->name = name; }

Explanation: The this pointer refers to the calling object.

3 Match each expression to its meaning

Term Meaning
this Pointer to the object
this->name Access to a member
*this Object the pointer points to
return *this; Return the object for chaining

All lessons in Intermediate