Home > Backend Development > C++ > Why Can't I Initialize Non-Const Static Members Inside a C Class?

Why Can't I Initialize Non-Const Static Members Inside a C Class?

Patricia Arquette
Release: 2024-12-12 16:19:11
Original
731 people have browsed it

Why Can't I Initialize Non-Const Static Members Inside a C   Class?

In-Class Initialization of Static Members in C

In C , defining a static member variable inside the class declaration is not permitted. This action results in the compilation error "ISO C forbids in-class initialization of non-const static member `j'".

Reasons for the Prohibition:

  • Code Efficiency: Initializing static members in the class declaration could lead to duplicate definitions when the class is included in multiple compilation units.
  • Control over Initialization: Static members often require specific initialization logic, which cannot be guaranteed when they are initialized inline in the class declaration.

Exception for Const Members:

Const static members are allowed to be initialized in the class declaration because they are not modified after initialization. This ensures code efficiency and eliminates the need for explicit initialization.

Implications for Standard Values:

In C, static variables are automatically initialized to 0 if they are not explicitly initialized. However, in C , static variables are not automatically initialized. You must manually initialize them either in the class declaration (for const members) or in a separate .cpp file.

Solution:

To define a non-const static member variable in C , you should initialize it in a separate .cpp file rather than in the class declaration.

For example:

// Header file
class Test {
 public:
  static int j;
};

// .cpp file
int Test::j = 0;
Copy after login

The above is the detailed content of Why Can't I Initialize Non-Const Static Members Inside a C Class?. 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