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!
You can't initialize members of the parent class in the derived class constructor initialization list. It doesn't matter whether they are protected, public or anything else.
In your example, member
something
is member ofParent
class, which means that it can only be initialized in the constructor initializer list ofParent
class.Maybe you can try it in that way using the keyword "using"
When the compiler comes across the initializer list, the derived class object is yet to be formed. The base class constructor has not been called till then. Only after the base class constructor has been called,
something
comes to being. Hence the problem. When you do not call the base class constructor explicitly, the compiler does that for you (by generating the appropriate trivial constructor for the base class). This causes thesomething
member to be default initialized.From C++0x draft:
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: