Is it stable to use something like this in a class's ctor initialization list during implicit assignment (no operators are overloaded):
class C{
public:
C(int _var): var(_var), i(var*var)
{}
private:
int var;
int i;
};
I'm getting some eratic results, why is this?
Yes.
You might want to get rid of the initialization order dependency, and write:
C(int _var): var(_var), i(_var*_var)
Basically, by making i depend on var, you must ensure that var is declared before i in the class.
Similarly, you can initialize something in C that is defined (and initialized) in a parent class, because the parent will be constructed before C.
Best practices dictate that you be aware of the above, and avoid situations that obfuscate any of that - maybe document i's dependence on var, so that the next programmer (maybe yourself) doesn't introduce an initialization order issue.
That code has defined meaning, assuming the multiplication doesn't overflow.
Be aware that it relies critically on the fact that var
is defined before i
in the class (order in the initializer list is irrelevant, all that matters is the order the members themselves are defined). Otherwise i
would be initialized using the unitialized data member var
.
But if you're getting erratic behavior with exactly that code, then the bug lies elsewhere.
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