views:

99

answers:

4

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?

A: 
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
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
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
sry, I didn't read it throughly ^^;
starcorn
+4  A: 

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

Daniel Earwicker
thanks, I found the answer too when google. hehe took me like 1min compared to 2-3min to write down the question...
starcorn
Lesson learned then, eh? ;) Never underestimate the search button.
mizipzor
+1  A: 
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
me too, kinda reminds me the ternary ifs, i.e. hard to remember how to write.
starcorn
A: 

Depends on coding conventions.

From Google's C++ style guide:

void set_some_var(int var) { some_var_ = var; }
int some_other_var_;
Yaroslav