Reputation: 1641
I somehow read that it is bad style to do object-creation in a constructor ... however, I forgot why it was considered to be bad style (especially when using dependency injection).
Here an example of object-creation in the constructor as pseudo-code:
Myclass
{
Myclass(MyMemberFactory& fac)
{
for(Some criteria)
push_back(fac.createMyMemberType());
}
vector<MyMemberType*> getMyMember();
{
return myMember_;
}
...
private:
vector<MyMemberType*> myMember_;
}
So you can use unit-testing without problems, because you can mock-away the MyMemberFactory. If I would move the for-loop in an seperated initialize-method, it would be necesarry to check for double-initialisation, and all getters would need first to ckeck, if initialisation already was done. Here the code, by using a seperate initialisation:
Myclass
{
Myclass() : isInitialized_(false)
{
}
void initialize(MyMemberFactory& fac);
{
if(isInitialized_)
throw "Error: Double-Init is not permitted.";
for(Some criteria)
push_back(fac.createMyMemberType());
isInitialized_ =true;
}
vector<MyMemberType*> getMyMember();
{
if(isInitialized_)
throw "Initialize first!";
return myMember_;
}
...
private:
vector<MyMemberType*> myMember_;
bool isInitialized_;
}
So do know any reason, why I should use the second approach over the first approach? Or maybe I just had something wrong in mind, and the first approach is perfectly ok?
Upvotes: 2
Views: 144
Reputation: 94409
The first approach is actually fine. It's not that object creation in a constructor is problematic, it's that doing so with a constructor is problematic. So
Myclass()
{
MyMemberFactory fac;
for(Some criteria)
push_back(fac.createMyMemberType());
}
Would be problematic since clients can no longer use a different factory (for testing, for instance).
Upvotes: 2
Reputation: 29966
If the constructor throws an exception, the destructor will not be called, thus you will lose all the memory that you manually allocated.
Upvotes: 3