Home > Backend Development > C++ > How to Initialize a Const Member Variable in a C Constructor?

How to Initialize a Const Member Variable in a C Constructor?

Mary-Kate Olsen
Release: 2024-11-03 02:54:03
Original
353 people have browsed it

How to Initialize a Const Member Variable in a C   Constructor?

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

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

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!

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