Home >Backend Development >C++ >Why Can\'t I Initialize a `const` Field in a Constructor Directly in C ?

Why Can\'t I Initialize a `const` Field in a Constructor Directly in C ?

Susan Sarandon
Susan SarandonOriginal
2024-11-03 12:50:31208browse

Why Can't I Initialize a `const` Field in a Constructor Directly in C  ?

Initializing Const Fields in Constructors

When defining a class with a const field that must remain immutable throughout the object's lifetime, it's crucial to initialize it correctly. Consider the following scenario:

Problem Statement:

You want to create a C class Bar that accepts a Foo pointer as input and maintains an immutable reference to it within its lifetime. The following code fails to compile:

<code class="cpp">class Foo;

class Bar {
public:
    Foo * const foo;
    Bar(Foo* foo) {
        this->foo = foo;
    }
};

class Foo {
public:
  int a;
};</code>

Solution:

To correctly initialize a const field in a constructor, you need to use an initializer list:

<code class="cpp">Bar(Foo* _foo) : foo(_foo) {
}</code>

Note that we renamed the incoming parameter to _foo to avoid name conflicts.

This approach ensures that the foo pointer is initialized as soon as the Bar object is constructed, and it remains immutable for the duration of its lifecycle.

The above is the detailed content of Why Can't I Initialize a `const` Field in a Constructor Directly in C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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