Initializing Const Fields in Constructors
When defining a class with a const field that must remain immutable throughout the object's lifetime, it's crucial to initialize it correctly. Consider the following scenario:
Problem Statement:
You want to create a C class Bar that accepts a Foo pointer as input and maintains an immutable reference to it within its lifetime. The following code fails to compile:
<code class="cpp">class Foo; class Bar { public: Foo * const foo; Bar(Foo* foo) { this->foo = foo; } }; class Foo { public: int a; };</code>
Solution:
To correctly initialize a const field in a constructor, you need to use an initializer list:
<code class="cpp">Bar(Foo* _foo) : foo(_foo) { }</code>
Note that we renamed the incoming parameter to _foo to avoid name conflicts.
This approach ensures that the foo pointer is initialized as soon as the Bar object is constructed, and it remains immutable for the duration of its lifecycle.
The above is the detailed content of Why Can\'t I Initialize a `const` Field in a Constructor Directly in C ?. For more information, please follow other related articles on the PHP Chinese website!