Home > Backend Development > C++ > body text

How to Initialize Protected Members of a Parent Class in a Child Class\'s Constructor?

Barbara Streisand
Release: 2024-10-25 04:45:02
Original
275 people have browsed it

How to Initialize Protected Members of a Parent Class in a Child Class's Constructor?

Initializing Protected Members with Initialization List

In object-oriented programming, parent classes can have protected members that are accessible by child classes. When initializing child objects, it may be desirable to also initialize the protected members declared in the parent class. However, this is not as straightforward as it seems.

Consider the following example:

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

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

In this example, we attempt to initialize the protected member something of the parent class using the initialization list of the child class' constructor. However, the compiler will report an error: class 'Child' does not have any field named 'something'. This error occurs because the protected member something is not declared in the child class and is therefore not visible within the initialization list.

Solution

To initialize protected members of a parent class within a child class' constructor, we need to add a constructor (preferably protected) to the parent class that takes the necessary parameters to initialize these members. The child class can then use this constructor to pass the appropriate values.

Here's a revised implementation:

<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 example, we have added a protected constructor to the Parent class that takes a string parameter and uses it to initialize the protected member something. The Child class then uses this constructor to initialize its parent's protected member during its own construction.

The above is the detailed content of How to Initialize Protected Members of a Parent Class in a Child Class\'s Constructor?. 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!