marcman marcman - 3 months ago 8
C++ Question

Must I initialize everything in the constructor?

I believe that anything uninitialized gets automatically initialized and that this is somewhat dangerous (and poor practice). I also understand that initialization lists are generally more efficient (and in some cases necessary), however, I wanted to verify some parameters via a function call, before assigning them to a member variable.

For example, using the typical assignment constructor, I'd have something like this:

class MyObj
{
private:
int one_;
int two_;
DiffObj diffObj_;

... // other stuff
}

MyObj::MyObj(int a, int b, std::string type, std::vector<double> params)
{
one_ = a;
two_ = b;
if (verifyType(type, params))
{
diffObj_ = createDiffObj(params);
}
}





With this situation though, how could I utilize an initialization list? I thought perhaps by initializing some of the parameters in the constructor and using a separate call to initialize the rest, but I am not quite sure if that is kosher.

MyObj::MyObj(int a, int b) :
one_(a),
two_(b)
{}

MyObj::initializeDiffObj(std::string type, std::vector<double> params)
{
if (verifyType(type, params))
{
diffObj_ = createDiffObj(params);
}
}

Answer

Something like this would be perfectly reasonable. You can have an initializer-list and do some work inside your constructor, you do not have to pick one.

 class MyClass {
     public:
         MyClass(int a, SomeStruct b)
          : _a(a) {
              if (isValid(b)) {
                   // Initialize _b
                   _b = createWeirdThingFromSomeStruct(b);
              }
         }
     private:
         int _a;
         WeirdThing _b;
};