Home > Backend Development > C++ > body text

When Can the Initialization List of a Child Class Constructor Be Used to Initialize Protected Data Members?

Linda Hamilton
Release: 2024-10-24 13:59:02
Original
669 people have browsed it

When Can the Initialization List of a Child Class Constructor Be Used to Initialize Protected Data Members?

Initialization List and Protected Member Initialization

In object-oriented programming using C , it is a common practice for classes to inherit from parent classes and extend their functionality. However, a question arises: can the initialization list of a child class' constructor be used to initialize data members declared as protected in the parent class?

In an attempt to achieve this, one may have code similar to the following:

<code class="cpp">class Parent {
protected:
    std::string something;
};

class Child : public Parent {
private:
    Child() : something("Hello, World!") {}
};</code>
Copy after login

However, this attempt will result in a compiler error, indicating that the class Child does not have a field named something. This is because the data member something is declared as protected in the parent class.

To initialize protected members using the initialization list of a child class, an alternative approach is required. A constructor with the required initialization can be added to the parent class, and this constructor can then be invoked from the child class' constructor. This can be achieved through constructor forwarding:

<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 modified code, a protected constructor is added to the Parent class, and it takes a string parameter. The Child class' constructor then invokes the Parent class' protected constructor using constructor forwarding to pass the necessary argument and initialize the something data member.

The above is the detailed content of When Can the Initialization List of a Child Class Constructor Be Used to Initialize Protected Data Members?. 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
Latest Articles by Author
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!