Home >Backend Development >C++ >How do you initialize a const member variable in a C constructor?
Maintaining Immutable Class Properties with Constructor Initialization
In C , constructors play a crucial role in establishing the initial state of an object. Occasionally, we encounter situations where certain class properties need to remain unaltered throughout the instance's lifetime. One common scenario is the assignment of a constant pointer during object creation.
Consider the following code snippet:
<code class="C++">class Foo; class Bar { public: Foo * const foo; Bar(Foo* foo) { this->foo = foo; } }; class Foo { public: int a; };</code>
The intention here is to create a Bar object with a non-modifiable pointer to a Foo instance. However, upon compilation, we encounter an error. This is because the "this" pointer is not directly accessible inside a class's constructor.
To overcome this issue, we must initialize the constant field in the constructor's initializer list using the following syntax:
<code class="C++">Bar(Foo* _foo) : foo(_foo) { }</code>
In this updated code, we rename the incoming parameter to avoid confusion with the instance member. Within the initializer list, we explicitly assign the value of the _foo argument to the foo constant member.
By using this technique, we effectively set the foo pointer to a const value during object construction, ensuring its immutability throughout the lifetime of the Bar instance.
The above is the detailed content of How do you initialize a const member variable in a C constructor?. For more information, please follow other related articles on the PHP Chinese website!