INFO: Initializing const Member Data

This article was previously published under Q92614
This article has been archived. It is offered "as is" and will no longer be updated.
The sample source code below demonstrates how to initialize a const memberof a class. Note that the code uses a member initialization list because aconst member may not appear on the left side of the assignment operator.The value must be set when the object is constructed because the value of aconst member can be set only at initialization.

If an application attempts to initialize a const member with the assignmentoperator, the compiler generates the following error messages:
error C2758: 'a' : must be initialized in constructor base/member initializer list

error C2166: lvalue specifies const object
Using Visual C++ 32-bit Edition, version 4.0, this error is reported as:
error C2166: l-value specifies const object
The member initialization list is the preferred method to initialize themembers of a class. For example, when initializing an object of a user-defined type, it is more efficient to use a member initialization list toinitialize a data member than to perform an assignment in the constructor.The latter approach requires two calls: one to construct the data memberand another to the operator=() function to assign a value to the member.

Sample Code

/* * Compile options needed: none */ #include <iostream.h>class demo{   const int a;public:   demo(int val = 0) : a(val) {}   int get_a(void) { return a; }};void main(){   demo first;   demo second(5);   cout << "First = " << first.get_a() << endl;   cout << "Second = " << second.get_a() << endl;}		

Output

First = 0Second = 5		
SUMMARY
Properties

Article ID: 92614 - Last Review: 12/04/2015 09:19:53 - Revision: 2.0

Microsoft Visual C++ 1.0 Professional Edition, Microsoft Visual C++ 1.5 Professional Edition, Microsoft Visual C++ 1.51, Microsoft Visual C++ 2.0 Professional Edition, Microsoft Visual C++ 2.1, Microsoft Visual C++ 4.0 Standard Edition, Microsoft Visual C++ 5.0 Enterprise Edition, Microsoft Visual C++ 5.0 Professional Edition

  • kbnosurvey kbarchive kbinfo kblangcpp KB92614
Feedback