Given some code such as
class Foo {
Bar b1;
Car c1;
Foo(const InitInfo& info) {
this->b1 = generateBar(info);
this->c1 = generateCar(info);
}
};
I cannot know the exact objects that can be assigned to b1 and c1 until I am in the constructor. There are two possible ways I can see to deal with this.
Firstly, default initialise b1 and c1 in the declaration (assuming they have constructors that allow for this) and then re-assign to them in the constructor.
Secondly, wrap the declarations of b1 and c1 in unique_ptrs so they get default initialised to nullptr and then assign the correct object to them in the constructor so they only get assigned an object to them once rather than twice.
The downside I can see the the first option is that if there is a destructor that relies on the contents of the object of Bar or Car then the destructor will be called twice, with one of those calls being for a default initialised object which may not have the correct data and could cause an error. Additionally, if the object doesn't have a default constructor then you will be stuck.
Which way would you recommend? If you have an alternative, what is that and how would that way be better than these two options given?