Home >Backend Development >C++ >How Can I Properly Initialize Constant Data Members in C ?
Initialization of Const Data Members: A Comprehensive Guide
Introduction:
Understanding the initialization of constant data members in C can be perplexing. This article aims to clarify this aspect by addressing a common error and providing a detailed explanation of the process.
Error Encountered:
Consider the following code snippet:
#include <iostream> using namespace std; class T1 { const int t = 100; public: T1() { cout << "T1 constructor: " << t << endl; } };
When attempting to initialize the const data member t within the class constructor, the following error occurs:
test.cpp:21: error: ISO C++ forbids initialization of member ‘t’ test.cpp:21: error: making ‘t’ static
Understanding the Error:
The error stems from the C language restriction that disallows the initialization of const data members within the class definition. This is because const variables require a unique definition, which cannot be guaranteed when included in multiple translation units.
How to Initialize Const Data Members:
To initialize a const data member, it must be defined outside the class definition. This can be achieved through the class initializer list:
T1() : t(100) {}
In the initializer list, t is assigned the value of 100 before the class initialization occurs. This ensures that the const data member is initialized upon object creation.
Conclusion:
Initializing const data members requires adherence to specific language rules. By defining them outside the class definition and using the initializer list, programmers can effectively initialize const data members and avoid the aforementioned error.
The above is the detailed content of How Can I Properly Initialize Constant Data Members in C ?. For more information, please follow other related articles on the PHP Chinese website!