Reputation: 24067
I wrote such class:
class FastDecoder
{
public:
FastDecoder(void);
~FastDecoder(void);
private:
SnapshotMessageBuilder messageBuilder;
DecodedMsg const& decodedMsg;
};
If it is correct to use messageBuilder
to initialize decodedMsg
?
FastDecoder::FastDecoder(void):
decodedMsg(messageBuilder.GetDecodedMsg())
{
I suspect that as FastDecoder is not yet constructed then not all fields are probaly initialized and so I can have runtime error triing to access messageBuilder
If my code is not good then how to rewrite it better? Will it keep working if I reorder fields like that:
private:
DecodedMsg const& decodedMsg;
SnapshotMessageBuilder messageBuilder;
Upvotes: 1
Views: 52
Reputation: 126462
Will it keep working if I reorder fields like that [...]?
No, because data members are initialized in the order in which they are declared in the class definition. As a result, the initialization of decodedMsg
would occur first, and that means you would be calling GetDecodedMsg()
on an object which has not been constructed yet.
Your current version, on the other hand, is OK, because messageBuilder
will have already been constructed by the time you are initializing decodedMsg
.
Upvotes: 3