Home > Backend Development > C++ > body text

Can Protected Parent Class Members Be Initialized via Child Class\'s Initialization List?

DDD
Release: 2024-10-25 06:07:02
Original
750 people have browsed it

Can Protected Parent Class Members Be Initialized via Child Class's Initialization List?

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!