Home > Backend Development > C++ > body text

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

Susan Sarandon
Release: 2024-11-03 12:50:31
Original
158 people have browsed it

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

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

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!

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