views:

195

answers:

3

I have a structure:

typedef struct {
   double x,y,z;
} XYZ;

I want to define a function like this:

double CalcDisparity(XYZ objposition, 
                     XYZ eyeposition, 
                     double InterOccularDistance = 65.0)

But I can't seem to find a way to assign a default value to eyeposition. How can I do this in C++?

+7  A: 

It's

struct XYZ{
    XYZ( double _x, double _y, double _z ) : x(_x), y(_y),z(_z){}
    XYZ() : x(0.0), y(42.0), z(0.0){}

    double x, y, z;
};

so that I now have a default constructor. Then you call it like this:

double CalcDisparity( XYZ objposition = XYZ(),
                      XYZ eyeposition = XYZ(),
                      double interOccularDistance = 65.0 )

But there's one small trick: you can't do a default value for the 1st and 3rd arguments only. One more thing: C is a language, C++ is another language.

wheaties
You can if you define additional constructors, eg: `struct XYZ { XYZ(double _x, double _z) : x(_x), y(42.0), z(_z) }; double CalcDisparity( XYZ objposition = XYZ(), XYZ eyeposition = XYZ(1.0, 2.0), double interOccularDistance = 65.0 );`
Remy Lebeau - TeamB
+1  A: 
  1. You could write a factory function for creating XYZ objects, and call the function as the default value.

  2. You could make NULL the default value, and then check in the function if the argument is NULL, creating a default XYZ if it is.

  3. Create a global XYZ object and assign it as the default.

  4. If you don't mind using C++ instead of pure C, make XYZ a class with a constructor.

Those are all ways that will compile and work, but some might not be good coding practices.

Colin
@Colin, if he's using C++ then he can leave it as a struct, but give it a constructor
Glen
+1  A: 

In C, function arguments cannot have default values (don't know about C++).

What you can do, in C, is pass a (somehow) invalid value, check for that invalid value and use another instead.

int foo(int n) {
  if (n == -1) { /* -1 is invalid */
    n = 42;      /* use 42 instead */
  }
  /* ... */
}
pmg
When this answer was given, the question was tagged 'C'; the tag has since been removed because C does not support default values for arguments.
Jonathan Leffler
C++ does support default values.
andand