what are some of the considerations when putting member variables in a initializer list......are there some instances when it makes no performace increase or sense to put it in there? I know const members variables have to be initialized in there.
what are some of the considerations when putting member variables in a initializer list......are there some instances when it makes no performace increase or sense to put it in there? I know const members variables have to be initialized in there.
basically when does it make sense to put things in the initializer list of the constructor?
I only do it when they have to be done there. As in the case of const variables and in the case where a member object's constructor requires a parameter. I just don't like how it looks when you have a huge list. But that's just me..... and I rule.
"You are stupid! You are stupid! Oh, and don't forget, you are STUPID!" - Dexter
Initialize your variables there whenever you can. If you just assign to them in the body of the constructor, the variable has to be constructed by the default constructor, then cleared and reassigned by the assignment operator. Doing it in the initializer list just invokes the copy constructor (or whatever constructor you wrote for it).Originally posted by noob2c
basically when does it make sense to put things in the initializer list of the constructor?
Not really. If you have a derived class, you can't initialize the base object's objects with it. So you may want to reassign the variables there.are there some instances when it makes no performace increase or sense to put it in there?
NOTE: most of the time you can avoid that by sending initialization data to the parent class for it to initialize objects. ie:
NOTE #2: All classes are constructed from Base to Derived. The Derived just shows what Base constructor to call; it doesn't call it itself.Code:class B { public: B(); B(int x) : value(x) {} private: int value; }; class A : public B { public: A(); A(int x) : B(x) {} };
ygfperson has hit it on the head; for variables that are automatically initialized (i.e. any non-primitive type), initializing in the list calls only the constructor, initializing in the body requires both constructor and copy operator are called.
There is another reason, as well. When the constructor exists completely as an initialization list (and the body is empty), the compiler may be able to optimize it better.