Reputation: 135
I have a class that has 2 members One of the members needs to be used to construct the other.
Definitions:
msat::tracker::Parser m_parser;
msat::tracker::TCPServer m_tcpServer;
In the constructor:
TrackerInterface::TrackerInterface(const core::logging::ILog& consoleLog,
const core::logging::IDataLog& dataLog,
core::event::IQueue& eventQueue)
: m_parser(consoleLog,dataLog,eventQueue),
m_tcpServer(consoleLog,m_parser,eventQueue,0,8,10)
{
}
So I create m_parser
first and pass it to the constructor of m_tcpServer
The code compiles but my question is are there any issues with this approach?
Upvotes: 2
Views: 81
Reputation: 238311
The code compiles but my question is are there any issues with this approach?
Potentially, yes.
If the member stores the reference to the other member rather than only needing it within the construction, and if your class is copyable or movable, then the implicitly generated constructors and assignment operators will leave the object in a state where one member does not refer or point to the other member of the same super object, and may even be left dangling.
In such case, you probably need to specify a class invariant that one member always refers or points to the other member of the same object, and you must implement custom copy and move constructors and assignment operators to enforce that invariant.
Other than that, you probably must also be careful to initialise the members in correct order. The members are initialised in order of declaration.
Upvotes: 2
Reputation: 24038
Yes that is the way to do it, just remember that the order of initializiation is based on the declaration order of the members and NOT the order of them in the initializer list:
12.6.2 Initializing bases and members
...
13 In a non-delegating constructor, initialization proceeds in the following order:
...
(13.3) — Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).
So just keep them declared in the order you have, and maybe add a comment telling that the order shouldn't be changed and everything is fine:
// Have to be declared in this order, because
// m_tcpServer has to be constructed using m_parser.
msat::tracker::Parser m_parser;
msat::tracker::TCPServer m_tcpServer;
Upvotes: 2