Frederick Gotham said:
John Carson posted:
Can't be done with a const object.
Right. While playing with your code, I deleted the const qualifier to get
rid of warnings about the assignment operator.
What if the constructor's parameters should determine the values?
MyClass(int argi, double argd) : obj({argi + 7, argd / 2}) {}
Then I think you need Victor's "constructor function".
If you were really desperate to use the static struct technique, then you
could create an extra member variable for the sole purpose of having its
constructor set the static struct object's values to the desired levels.
This would need to appear before the MyStruct object within MyClass. I
recommend against it, however, since it is ugly and increases the size of
your class.
struct MyStruct {
int i;
double d;
};
class MyClass
{
private:
struct Auxiliary
{
Auxiliary()
{
ms.i = 5;
ms.d = 45.67;
}
Auxiliary(int argi, double argd)
{
ms.i = argi + 7;
ms.d = argd/2;
}
};
Auxiliary a;
const MyStruct obj;
static MyStruct ms;
public:
MyClass() : obj(ms)
{}
MyClass(int argi, double argd) : a(argi, argd), obj(ms)
{}
};
MyStruct MyClass::ms;
int main()
{
MyClass obj1, obj2(20, 5);
return 0;
}