Home >Backend Development >C++ >How Can I Initialize Const Data Members in C ?

How Can I Initialize Const Data Members in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-12-09 15:29:15935browse

How Can I Initialize Const Data Members in C  ?

Initializing Const Data Members

When attempting to initialize a const data member within a class definition, you may encounter an error message stating that C forbids such initialization. This error arises because const variables, as the name suggests, are constant and cannot be modified once initialized.

To initialize a const data member, we need to declare it within the class but define it outside the class. This approach ensures that the definition occurs before any instance of the class is created.

class T1 {
  const int t;

public:
  T1() : t(100) {
    cout << "T1 constructor: " << t << endl;
  }
};

In the class definition, we declare the const data member t without assigning any value. The actual initialization takes place in the constructor's initializer list, which is executed before the constructor body.

This method allows us to initialize const data members while adhering to the principle that const variables cannot be modified during program execution. By separating the declaration and definition, we ensure that the t variable is assigned a constant value at compile time and cannot be altered afterward.

The above is the detailed content of How Can I Initialize Const Data Members 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