Initialize parent's protected members with initialization list (C++)

Stephen picture Stephen · Feb 18, 2010 · Viewed 48.7k times · Source

Is it possible to use the initialization list of a child class' constructor to initialize data members declared as protected in the parent class? I can't get it to work. I can work around it, but it would be nice if I didn't have to.

Some sample code:

class Parent
{
protected:
    std::string something;
};

class Child : public Parent
{
private:
    Child() : something("Hello, World!")
    {
    }
};

When I try this, the compiler tells me: "class 'Child' does not have any field named 'something'". Is something like this possible? If so, what is the syntax?

Many thanks!

Answer

philsquared picture philsquared · Feb 18, 2010

It is not possible in the way you describe. You'll have to add a constructor (could be protected) to the base class to forward it along. Something like:

class Parent
{
protected:
    Parent( const std::string& something ) : something( something )
    {}

    std::string something;
}

class Child : public Parent
{
private:
    Child() : Parent("Hello, World!")
    {
    }
}