简体   繁体   中英

Is it possible to initialize new object in constructor's initialization list and reference it?

Client is the top class of DLL so I need to create and pass new Session object in it's initialization to create requestor and session should be assigned to same Session. Is it possible?

class Session
{
public:Session() {}

};

class Requestor
{
public: Requestor(const Session& session) {};
};

class Client
{
public:Client()
{
    Session newSession;
    requestor = Requestor(newSession);
}

private:
    Session session;
    Requestor requestor;
};

It is possible, but somewhat fragile in that the initialization order depends on the declaration order of the members. Provided these remain as in your example, you can simply do

class Client()
{
public:
    Client() : requestor(session) // session is implicitly default constructed
    {}
private:
    Session session;
    Requestor requestor;
};

Note: it isn't clear why you are instantiating a local Session object in your constructor. I am assuming that is a mistake.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM