Skip to content
Advertisement

C++ equivalent to Java this

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)
{
//?
}

Advertisement

Answer

Same word: this

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

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