Home >Backend Development >C++ >Can Child Classes Initialize Protected Parent Members Through Initialization Lists?
When inheriting a class with protected data members, it may be desirable to initialize them using the initialization list of the child class's constructor. However, this approach often leads to compilation errors.
In this example:
<code class="cpp">class Parent { protected: std::string something; }; class Child : public Parent { private: Child() : something("Hello, World!") {} };</code>
Compiling this code will result in an error, as the child class Child does not have a member named something.
To resolve this, the parent class Parent must define a constructor that initializes the protected member something. This constructor can be declared protected, allowing derived classes to access it.
The modified code below will compile successfully:
<code class="cpp">class Parent { protected: std::string something; Parent(const std::string& something) : something(something) {} }; class Child : public Parent { private: Child() : Parent("Hello, World!") {} };</code>
In this modified code, the protected constructor in the Parent class forwards the initialization argument to the something member, enabling the child class to initialize the parent's protected member during its own initialization.
By following this syntax, it becomes possible to initialize protected parent members using the child class's initialization list, providing greater control and flexibility in object initialization across inheritance hierarchies.
The above is the detailed content of Can Child Classes Initialize Protected Parent Members Through Initialization Lists?. For more information, please follow other related articles on the PHP Chinese website!