Home > Backend Development > C++ > How do you initialize a const member variable in a C constructor?

How do you initialize a const member variable in a C constructor?

Patricia Arquette
Release: 2024-11-03 02:58:29
Original
1002 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template