Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it stable to use arithmetic in a ctor's initialization list?

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?

like image 609
user965369 Avatar asked Nov 19 '11 16:11

user965369


2 Answers

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.

like image 122
Mordachai Avatar answered Sep 21 '22 15:09

Mordachai


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.

like image 37
Steve Jessop Avatar answered Sep 23 '22 15:09

Steve Jessop