Home > Backend Development > C++ > How to Initialize `const` Array Members in C Using Constructor Initialization Lists?

How to Initialize `const` Array Members in C Using Constructor Initialization Lists?

Barbara Streisand
Release: 2024-11-03 17:26:03
Original
596 people have browsed it

How to Initialize `const` Array Members in C   Using Constructor Initialization Lists?

Using Constructor Initialization Lists to Initialize Const Array Members

In C , class members with the const qualifier are considered constant and cannot be modified after initialization. This raises the question of how to initialize such members in class initializer lists. Consider the following class definition:

<code class="cpp">class MyClass {
public:
    const int arr[2];
};</code>
Copy after login

It is not possible to initialize arr within the constructor function body because it is declared const. However, C 11 introduced a new feature that allows initializing const members in the constructor initialization list.

<code class="cpp">struct MyClass {
    const int arr[2];

    MyClass() :
        arr{ 2, 3 }
{
    // Other construction logic
}
};</code>
Copy after login

In this example, the arr member is initialized with the values {2, 3} in the constructor initialization list. This allows for the creation of multiple instances of MyClass with different constant values for arr.

The above is the detailed content of How to Initialize `const` Array Members in C Using Constructor Initialization Lists?. For more information, please follow other related articles on the PHP Chinese website!

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