Initializing a Constant Pointer Member in a C Constructor
When working with classes in C , we may encounter situations where we need to initialize a pointer member as a constant within the constructor. This ensures that the pointer remains immutable throughout the object's lifetime.
Consider the following code example:
<code class="cpp">class Foo; class Bar { public: Foo * const foo; Bar(Foo* _foo) { foo = _foo; } };</code>
In this code, the foo member is marked as a constant pointer. However, the compilation will fail because the foo pointer is assigned within the constructor body, which is not allowed for constant members.
Correct Method: Initializing in the Initializer List
The correct way to initialize a constant pointer member is to do so in the member initializer list within the constructor's body. This can be achieved as follows:
<code class="cpp">class Bar { public: Foo * const foo; Bar(Foo* _foo) : foo(_foo) { } };</code>
By initializing foo in the initializer list, the compiler ensures that the pointer is assigned its value before the constructor enters its body. This satisfies the requirement for constant members to be initialized upon object construction.
In the revised code, the incoming parameter variable is renamed to _foo to avoid confusion with the foo member.
By following this approach, you can initialize constant pointer members in the constructor, ensuring that their values remain immutable throughout the object's lifecycle.
The above is the detailed content of How to Initialize a Constant Pointer Member in a C Constructor?. For more information, please follow other related articles on the PHP Chinese website!