C++ equivalent to Java this

nobody picture nobody · Aug 2, 2011 · Viewed 20.6k times · Source

In Java you can refer to the current object by doing: this.x = x. How do you do this in C++?

Assume that each of these code examples are part of a class called Shape.

Java:

public void setX(int x)
{
this.x = x;
}

C++:

public:
void setX(int x)
{
//?
}

Answer

Benjamin Lindley picture Benjamin Lindley · Aug 2, 2011

Same word: this

Only difference is it is a pointer, so you need to use the -> operator:

void setX(int x)
{
    this->x = x;
}