Home > Backend Development > C++ > body text

How to Initialize `const` Fields in C Constructors?

DDD
Release: 2024-11-02 21:19:03
Original
520 people have browsed it

How to Initialize `const` Fields in C   Constructors?

Initializing Const Fields in Constructors

Consider the scenario where a C class Bar requires a Foo pointer and intends to keep it immutable throughout its lifecycle. How should this be implemented?

Initially, it might seem straightforward to initialize the const field within the constructor, as shown below:

<code class="cpp">class Foo;

class Bar {
public:
    Foo * const foo;
    Bar(Foo* foo) {
        this->foo = foo;
    }
};

class Foo {
public:
  int a;
};</code>
Copy after login

However, this approach fails to compile. The solution lies in using an initializer list:

<code class="cpp">Bar(Foo* _foo) : foo(_foo) {
}</code>
Copy after login

Note that the incoming variable has been renamed to prevent naming conflicts. This initializer list initializes the const field at the very beginning of the constructor, ensuring its immutability.

The above is the detailed content of How to Initialize `const` Fields in C Constructors?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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!