Is arithmetic use stable in ctor initialization list?

Is it possible to use something similar in the initialization list of the ctor class with implicit assignment (without overloading statements):

class C{ public: C(int _var): var(_var), i(var*var) {} private: int var; int i; }; 

I get some resulting results, why is this?

+7
source share
3 answers

Yes.

You can get rid of the initialization order dependencies and write:

  C(int _var): var(_var), i(_var*_var) 

Basically, making me depend on var, you must make sure that var is declared before I'm in the class.

Similarly, you can initialize something in C that is defined (and initialized) in the parent class, because the parent will be created before C.

Best practices dictate that you should be aware of this above, and to avoid situations that obfuscate any of them - perhaps I am dependent on the document for var, so the next programmer (maybe you yourself) does not introduce a problem with the initialization order.

+8
source

This code defined the value, assuming multiplication is not overflowing.

Keep in mind that he critically relies on the fact that var is defined before i in the class (the order in the initializer list does not matter, all that matters is the order that determines the members themselves). Otherwise, i will be initialized using the var unified data element.

But if you get erratic behavior with this particular code, then the error is somewhere else.

+5
source

Yes, it is safe, but in this case you have to be careful. You are using var , not _var , so you must be sure that var built before i . This is the case here because the members are built in the order of their declaration (in this case var , i ), which may differ from the order in which they appear in the initializer list.

So in this case it works. It will also work in this case:

 C(int _var): i(var*var), var(_var) 

but not this:

 class C{ public: C(int _var): var(_var), i(var*var) {} private: int i; int var; }; 

But of course, to be always safe, you could just use _var :

 C(int _var): var(_var), i(_var*_var) 
+5
source

All Articles