Visual C++ 7.1Visual C++ 7.0Windows 2003Windows 2000Visual C++ 6.0Windows XPIntermediateDevVisual StudioWindowsC++
How to implement a default value for a struct parameter






2.47/5 (34 votes)
Dec 12, 2003

141704
How to implement a default value for a struct parameter.
Introduction
Someone asked me how to implement a default parameter value for a struct
. He wanted to make it possible to make the following calls:
MyStruct st = {200,50); foo(); // No parameters means the default ones foo(st); // Use the parameters passed
He had tried the following:
struct MyStruct { int a; int b; }; void foo(MyStruct st={100,100}) { cout << st.a << " " << st.b << endl; }
The compiler (VC 6) however didn't compile this.
Solutions
You can use a constructor in your struct
. It's not really nice but it will work.
struct MyStruct { MyStruct(int x, int y) { a = x; b = y; } int a; int b; }; void foo(MyStruct st=MyStruct(100,100)) { cout << st.a << " " << st.b << endl; }
The second solution, I like a little more:
struct MyStruct { int a; int b; };
static const MyStruct stDefValue = { 100, 100 }; void foo(MyStruct st=stDefValue) { cout << st.a << " " << st.b << endl; }
Conclusion
It's not a big deal and you may find it not nicely programmed in an OO way, but it is handy to know when you want to do something like this.