Search code examples
c++initializationderived-class

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)
    {}
}

Solution

  • 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)
    {}