Home >Backend Development >C++ >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!