0

In Java you can access variables in a class by using the keyword this, so you don't have to figure out a new name for the parameters in a function.

Java snippet:

private int x;

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

Is there something similar in C++? If not, what the best practice is for naming function parameters?

starcorn
  • 8,261
  • 23
  • 83
  • 124

4 Answers4

4

If you want to access members via this, it's a pointer, so use this->x.

Daniel Earwicker
  • 114,894
  • 38
  • 205
  • 284
1
class Example {
    int x;
    /* ... */
public:
    void setX(int x) {
        this->x = x;
    }
};

Oh, and in the constructor initialization list, you don't need this->:

Example(int x) : x(x) { }

I'd consider that borderline bad style, though.

Sean
  • 29,130
  • 4
  • 80
  • 105
0
private int x;

public int setX(int newX) {
  x = newX;
  return x;  //is this what you're trying to return?  
}

In most cases, I will make a 'set' function like this void IE

public:
void setX(int newX) {
  x = newX;
}
David Oneill
  • 12,502
  • 16
  • 58
  • 70
  • no I want to set the data member with the value from the parameter. Anyway I figure out that you need to write `this->x = x;` – starcorn Feb 09 '10 at 21:07
  • Uh, I **am** setting the data member to the value of the parameter. Doing this->x is unnecessary. However, I'm glad you learned how to use the 'this' pointer correctly. – David Oneill Feb 09 '10 at 21:31
0

Depends on coding conventions.

From Google's C++ style guide:

void set_some_var(int var) { some_var_ = var; }
int some_other_var_;
Yaroslav
  • 2,718
  • 17
  • 16