Reputation: 523
I have the following code, and would like to give default value for param3. I have tried various attempts, and compiler's error msg seems to be saying in class non-int initialization is not allowed.
Is this a bad practice and why? What's a better approach from a OO perspective?
thanks
struct MyStruct
{
int a;
int b;
};
class myClass {
public:
void init(int param1 = 0, int param2 = 0, MyStruct param3);
}
Upvotes: 0
Views: 240
Reputation: 91
Probably the simplest and clearest way to solve a problem like this would be to do something like this:
class myClass {
public:
void init(int p1 = 0, int p2 = 0)
{
MyStruct s; //initialize this to whatever default values
init(p1, p2, s);
}
void init(int p1, int p2, MyStruct p3);
}
Upvotes: 0
Reputation: 14360
You could add a constructor and a default constructor MyStruct
and make a constant default value like this:
struct MyStruct {
int a;
int b;
MyStruct(int x, int y):a(x), b(y) {} // Constrctor.
MyStruct():a(0), b(0) {} // Default constrctor.
};
const MyStruct default_(3, 4); // for instance here by default a == 3 and b == 4
class myClass {
public:
void init(int param1 = 0, int param2 = 0, MyStruct param3 = default_);
};
Upvotes: 1
Reputation: 1117
This will work in C++0x.
struct MyStruct
{
int a;
int b;
};
function foo(int a, structure s = structure{10,20})
{
//Code
}
Upvotes: 0
Reputation: 6424
The following will work (at least with C++11):
void init(int param1 = 0, int param2 = 0, MyStruct param3 = MyStruct{ 2, 3 });
Upvotes: 0