Reputation: 2358
I am writing a C++ application that makes use of plenty of child objects nested within one 'root' object.
Each of these needs to be initialized in a specific order, with various operations being done between each initialization, and sometimes needing to have previously-initialized ones as arguments to each other.
However, my compiler is forcing me to initialize these in the constructor's initializer list, insisting that initializing within the constructor is not enough. For example, I could not do the following:
SomeThing::SomeThing() {
int argGottenByLibraryCall;
someLibraryCallToGetArg(&argGottenByLibraryCall);
m_ChildObject = ChildClass(argGottenByLibraryCall);
}
I have taken to implementing a post-creation initializer function instead:
SomeThing::SomeThing() : m_ChildObject() {
int argGottenByLibraryCall;
someLibraryCallToGetArg(&argGottenByLibraryCall);
m_ChildObject.Initialize(argGottenByLibraryCall);
}
This, however, seems like a poor practice for me to follow. Is there a better way of making my compiler (VC++ 2017) accept initialization within the constructor body?
Upvotes: 1
Views: 690
Reputation: 93324
This, however, seems like a poor practice for me to follow.
The poor practice is not using initialization lists. They allow you to mark your data members as const
and also ensure that they are initialized.
The correct way to solve your problem is to restructure your code so that m_ChildObject
has a proper constructor that can be used in the member initialization list.
If that is not possible, wrap your initialization logic in a function and use that in the member initialization list:
ChildObjectType makeChildObject() {
int argGottenByLibraryCall;
someLibraryCallToGetArg(&argGottenByLibraryCall);
ChildObjectType result;
result.Initialize(argGottenByLibraryCall);
return result;
}
// ...
SomeThing::SomeThing() : m_ChildObject(makeChildObject()) { }
Upvotes: 2