Let's say I have the following struct:
struct myStruct
{
 int x;
 int y;
 int z;
 int w;
};
I want to initialize this struct to a default value when calling the following function. If it helps I'm looking for a simple zero initialization.
void myFunc(myStruct param={0,0,0,0})
{
 ...
}
This code however gives me compile error. I've tried VS2003 and VS2008.
NOTE: I have looked at other answers mentioning the use of constructor. However I want the user to see what values I'm using for initialization.
Adding default constructor in to your myStruct will solves your problem.
struct myStruct {
   myStruct(): x(0),y(0), z(0), w(0) { }   // default Constructor
   int x, y, z, w;
};
Function declaration:
void myFunc(myStruct param = myStruct());
                        For modern C++ compilers which fully implement value-initilization it is enough to have the following value-initialized default value to zero-initiliaze data members of the myStruct:
myFunc(myStruct param=myStruct())
For other compilers you should to use something like this:
myStruct zeroInitilizer() {
   static myStruct zeroInitilized;
   return zeroInitilized;
}
myFunc(myStruct param=zeroInitilizer())
To avoid compiler specifics conside to use http://www.boost.org/doc/libs/1_53_0/libs/utility/value_init.htm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With