Hassan Syed
Hassan Syed

Reputation: 20485

C++: The choices of initializing a member class with no implicit default constructor (more constraints in question body)

boost::posix_time::time_duration has three constructor overloads, and no implicit constructor. I need to make some calculations in a class which has some time_duration members before I can initialize them. All of this implies that without a default constructor I do not have the luxury of preparing input for my class members in my composing class constructor.

The pattern might be described as follows (which is eroneous):

class X {
public:
    x(int i,int j){}
};

class Y {
  x _x; 
public:
    y() {i = 1+1; j=1-1; _x(i,j);}
};

int main()
{
    return 0;
}

I would like some relevant ways of constructing Y (with motivation), where

  1. X does not have a default constructor.
  2. X cannot be altered directly (but can be subclassed).
  3. The generated code is deterministic (no unnecesary expensive constructs malloc/vtables etc).
  4. crucial point The class Y has n X members and m possible calculations. Where n >1 and m > 1. So elegance is important.
  5. Unit testing considerations are important.

At this point I am leaning towards either subclassing , or calling functions to do the calculations and calling these functions in the initialization list (if that is even possible). You can comment on these approaches :D.

Upvotes: 1

Views: 141

Answers (1)

icecrime
icecrime

Reputation: 76755

Sorry if I misunderstood your question, but isn't Boost.Optional a solution to your problem ? That's probably the best way to achieve a default uninitialized state without going for pointers and dynamic allocation.

However, although that would work, it's probably not ideal. My solution of choice would probably be, if possible, to move the calculations in free functions in an anonymous namespace :

namespace {
    x computeX()
    {
        int i, j = /* ... */;
        return x(i, j);
    }
}

y::y()
  : _x(computeX())
{
    /* ... */
}

Upvotes: 4

Related Questions