1

So this question is probably a duplicate but when I search I don't find anything. So in C++ if I have

class Foo{
    public:
        int x;
        int y;
        Foo(int x, int y);
};

and

Foo(int xIn, int yIn){
    x = xIn;
    y = yIn;
}

isn't there a way to do the assignment with this? So you don't have to change the name for the variables being passed in?

Tommy K
  • 1,759
  • 3
  • 28
  • 51

4 Answers4

6

Yes, there is:

Foo(int x, int y) {
    this->x = x;
    this->y = y;
}

Here x and y hide the member variables, but you can use this->x and this->y to access them.

user253751
  • 57,427
  • 7
  • 48
  • 90
2

The idiomatic way is to use the initialization list:

Foo(int x, int y) : x(x), y(y) {}

Of course, if for whatever reason you want to access the hidden data members in the body of the constructor, you can use the this pointer:

Foo(int x, int y) {
    this->x = x;
    ....
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

In C++11, the preferred way to do this is

class Foo{
    int x;
    int y;

public:
    Foo(int x, int y): x{x}, y{y}{}
};

Or the traditional way ,

class Foo{
    int x;
    int y;
public:

    Foo(int x, int y): x(x), y(y){}
};
CS Pei
  • 10,869
  • 1
  • 27
  • 46
  • what's the difference between using {x} and (x)? And what does the empty {} signify at the end? – Tommy K Feb 10 '15 at 21:09
  • The end {} Is the function body (empty). the differences between {} and () for initialization can be found at http://stackoverflow.com/questions/24307913/c11-difference-in-constructors-braces – CS Pei Feb 10 '15 at 21:12
  • One more question, I'm using a separate header file which has all my function prototypes along with the .cpp file. So from your examples it looks like I would do `Foo(int x, int y) ... ` in the header, is that correct? Do I then have to do anything in the .cpp file? – Tommy K Feb 10 '15 at 21:22
  • 1
    You can implement the constructor in the header file or in the cpp files. Both are fine. But for a very small constructor, you can just put it in the header. – CS Pei Feb 10 '15 at 21:30
1

If you are trying to observe scope rules and also maintain clarity, you can always use the class scope operator while assigning the variables

class Foo{
public:
    int x;
    int y;
    Foo(int x, int y);
};

Foo(int x, int y) {
   Foo::x = x;
   Foo::y = y;
}
ivanw
  • 491
  • 8
  • 16