| Home | Libraries | People | FAQ | More

### Bypassing unnecessary default construction

Suppose we have class `Date`, which does not have a default constructor: there is no good candidate for a default date. We have a function that returns two dates in form of a `boost::tuple`:

    boost::tuple<Date, Date> getPeriod();

In other place we want to use the result of `getPeriod`, but want the two dates to be named: `begin` and `end`. We want to implement something like 'multiple return values':

    Date begin, end; // Error: no default ctor!
    boost::tie(begin, end) = getPeriod();

The second line works already, this is the capability of Boost.Tuple library, but the first line won't work. We could set some invented initial dates, but it is confusing and may be an unacceptable cost, given that these values will be overwritten in the next line anyway. This is where `optional` can help:

    boost::optional<Date> begin, end;
    boost::tie(begin, end) = getPeriod();

It works because inside `boost::tie` a move-assignment from `T` is invoked on `optional<T>`, which internally calls a move-constructor of `T`.