Home  >  Article  >  Backend Development  >  How to Initialize `const` Fields in C Constructors?

How to Initialize `const` Fields in C Constructors?

DDD
DDDOriginal
2024-11-02 21:19:03522browse

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>

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

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

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!

Statement:
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