views:

86

answers:

4

I am trying to pass a coordinate, which is defined as struct with 2 integer parameters (the struct is called coord) the following way:

UpdateB({0,0}); 

where the input argument is of type coord (i.e. in the above statement I am trying to pass a coordinate 0,0). UpdateB is some function. I am getting an error, any ideas what the problem could be?

+7  A: 

Make a constructor accepting two argumnets. Pass it as follows:

MyFunc(Point2d(0,0));

Pavel Radzivilovsky
+2  A: 

Pavel's got it spot on. If you want to create the struct instance as you're passing it to the function, you'll need to make a constructor for it. Then create a new instance of coord as the argument you're passing to the function. For the struct, something like...

struct coord
{
    int x, y;

    coord(int xvalue, int yvalue)
    {
        x = xvalue;
        y = yvalue;
    }
};

...should do the trick. Then just run...

UpdateB(coord(x, y));

...where x and y are your values.

Lewis
A better constructor declaration is with initialization list:struct coord { coord(int xvalue, int yvalue) : x(xvalue), y(yvalue) {} int x, y;}
ognian
+1  A: 

The syntax you are using would be valid C++0x (uniform initializers) and valid C99 (compound literals).
In C++03 you have to use either user-defined constructors or helper functions, the curly-brace syntax only works for aggregate initialization.

If your struct is a POD and you need it to stay one, you have to use a helper function:

coord make_coord(int x, int y) {
    coord c = {x, y};
    return c;
}

UpdateB(make_coord(x, y));

Otherwise, as already mentioned, give it a constructor

Georg Fritzsche
I have seen before `UpdateB( (coord){1,2} )` working in g++ (no need for the helper function), but I doubt whether this is proper C++...
David Rodríguez - dribeas
@David: In C++98/03 it isn't, g++ supports compound literals as an extension.
Georg Fritzsche
A: 

Pavel Radzivilovsky's solution is right (+1).

However you have to know that the coming new standart C++0x will allow the syntax of your example if you provide a constructor with two parameters (and maybe if you provide a constructor with initializer list but that's not useful here).

This feature is already available in GCC starting v4.4, if you use it you can enable it by enabling C++0x.

Klaim