简体   繁体   中英

Order of initialization in derived classes

I am trying to initialize some members of the base class through its constructor but I fail. In the following code it seems that derived class member message is not initialized before calling the base constructor. A workaround would be to have Child(string messg_arg) : message(messg_arg), Parent(messg_arg) , but is there any way to avoid this?

class Parent
{
protected:
    string something;
    Parent(string something_arg) : something(something_arg)
    {}   

}

class Child : public Parent
{
public:
    string message;
    Child(string messg_arg) : message(messg_arg), Parent(message)
    {}
}

The base class constructor is called before any member constructors in the derived class. This should work fine:

Child(string messg_arg) : Parent(messg_arg), message(messg_arg)
{}

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