Parad0x13
Parad0x13

Reputation: 2065

C++ constructor automatic variable assign

Let's say I have the class:

class foobar {
public:
    foobar(int _x, int _y) {
        x = _x;
        y = _y;
    }
    int x, y;
};

Is there any way to assign x and y to the values passed to foobar(int, int) instead of assigning them myself?

[Answer] Initialization Lists is what I need to use (Thanks all for clarifying)

I can write the code as such:

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

That means I don't have to underscore my input arguments either x(x) will work as intended

Upvotes: 1

Views: 6877

Answers (2)

Pierre Fourgeaud
Pierre Fourgeaud

Reputation: 14510

You can use the member-initialization-list. It is still your job but it is a better practice:

foobar(int _x, int _y): x(_x), y(_y) {
//                    ^^^^^^^^^^^^^^
}

If you really don't want to assign those values you can initialize those members with a class with no constructors (aggregate class):

class foo
{
public:
    int x, y;
};
foo{1, 2}; // <= Braces initialization

Working example: http://ideone.com/NlbkKb.

Upvotes: 4

Kerrek SB
Kerrek SB

Reputation: 477020

If your class is an aggregate, you can initialize it with the brace syntax:

class foobar
{
public:
    int x;
    int y;
};

foobar f { 1, 2 };

Otherwise, you should initialize the elements in the constructor:

class foobar
{
public:
    foobar(int x_, int y_) : x(x_), y(y_)  {  }
private:
    int x;
    int y;
};

foobar f(1, 2);

(You can also use the brace syntax in the second case.)

Upvotes: 3

Related Questions