Initializing Parent Class's Protected Data Members in Child Class's Initialization List
In object-oriented programming, derived classes can inherit features from their base classes. One question that often arises is whether it's possible to initialize protected data members of the parent class using the initialization list of the child class's constructor.
Consider the following code example:
<code class="cpp">class Parent { protected: std::string something; }; class Child : public Parent { private: Child() : something("Hello, World!") { } };</code>
When attempting to compile this code, the compiler throws an error, stating that the "Child" class does not contain a data member named "something." This is because the initialization list is only allowed to initialize data members within the child class itself.
To achieve the desired functionality, it's necessary to add a constructor to the parent class that accepts the desired initial value and forwards it to the base class's data member. For example:
<code class="cpp">class Parent { protected: Parent(const std::string& something) : something(something) {} std::string something; }; class Child : public Parent { private: Child() : Parent("Hello, World!") { } };</code>
In this case, the "Parent" class's constructor initializes the "something" protected data member when invoked from the child class's initialization list. Thus, the child class inherits the initialized "something" data member from its parent class.
The above is the detailed content of Can Protected Parent Class Members Be Initialized via Child Class\'s Initialization List?. For more information, please follow other related articles on the PHP Chinese website!