Home > Backend Development > C++ > How to Properly Initialize Const Data Members in C ?

How to Properly Initialize Const Data Members in C ?

Mary-Kate Olsen
Release: 2024-12-05 00:42:11
Original
424 people have browsed it

How to Properly Initialize Const Data Members in C  ?

Const Data Member Initialization in C

In C , when attempting to initialize a const data member within a class declaration, errors such as "ISO C forbids initialization of member" and "making 't' static" may arise. To resolve this, it's essential to understand the nature of const data members.

Const variables indicate a value that cannot be modified during program execution. However, C mandates that object definitions have unique declarations. To adhere to this rule, const variables cannot be defined within class declarations.

The solution lies in defining the const variable outside the class declaration, using the initializer list. The syntax for initializing a const data member is:

className() : memberName(value) {}
Copy after login

In your example:

#include <iostream>

using namespace std;

class T1
{
  const int t;

public:
  T1() : t(100) {}
};

int main()
{
  T1 obj;
  cout << "T1 constructor: " << obj.t << endl;
  return 0;
}
Copy after login

This code initializes the const data member t with the value 100 during object construction, avoiding the aforementioned errors.

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