32

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)
{
//?
}
Ferruccio
  • 98,941
  • 38
  • 226
  • 299
nobody
  • 323
  • 1
  • 3
  • 4

3 Answers3

40

Same word: this

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

void setX(int x)
{
    this->x = x;
}
Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
  • Not relevant, but I remember Stroustrup somewhere saying that making this a pointer in C++ was 'probably a mistake'. – jahhaj Aug 02 '11 at 05:59
  • 4
    That's not entirely accurate. `this` as a pointer predates references; had references been invented earlier then `this` would have been a reference. – MSalters Aug 02 '11 at 07:55
8

The C++ equivalent is this, but there are a few differences.

This is a pointer to the object in question, not a reference; so, you must use pointer dereferencing operators before accessing fields or methods.

(*this).method(...)
(*this).field

or, using the more popular syntax

this->method(...)
this->field    
Edwin Buck
  • 69,361
  • 7
  • 100
  • 138
3

The C++ equivalent is this; that is, the keyword is the same.

Paul Sonier
  • 38,903
  • 3
  • 77
  • 117