How to Initialize an Immutable Field in a Constructor: An in-Depth Exploration
In C , it is possible to encounter a scenario where you intend to create a class that requires an immutable field within its constructor. In such a case, ensuring the field's immutability is crucial. This article will delve into the proper approach to achieving this objective.
Consider a scenario where class Foo serves as a data structure, and class Bar is a wrapper around Foo that requires a Foo pointer as an argument during construction. Our goal is to guarantee that this pointer remains unchangeable throughout the lifetime of a Bar instance.
An attempt to initialize the const pointer foo within Bar's constructor might resemble the following:
<code class="cpp">class Foo; class Bar { public: Foo * const foo; Bar(Foo* foo) { this->foo = foo; // Compiler error } }; class Foo { public: int a; };</code>
However, this approach triggers a compilation error. To rectify it and establish the immutability of foo within Bar instances, we need to employ an initializer list:
<code class="cpp">Bar(Foo* _foo) : foo(_foo) {}</code>
In this revised version, the constructor takes a Foo pointer as an argument, assigns it to the member variable foo using the initializer list, and renames the incoming variable to avoid potential confusion with the member variable.
This technique ensures that the foo pointer is initialized immediately upon Bar's construction, rendering it immutable for the rest of the Bar instance's lifetime.
The above is the detailed content of How to Initialize a Const Member Variable in a C Constructor?. For more information, please follow other related articles on the PHP Chinese website!