
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to initialize const member variable in a C++ class?
A const member variable in a C++ class is a data member whose value must be initialized during object construction and cannot be modified.
Initializing Const Member Variable in C++ Class
The const member variable must be initialized. To initialize a const member variable, you can use a member initializer list using a constructor,. The member initializer list is the special way to initialize the values to class variables while creating an object before the constructor block runs.
Note: If the member is static and of an integer type, you can directly initialized with the class definition.
class Name { static const int age = 20; };
Syntax
Following is the basic syntax of initializer list of constructor:
class Stu { public: // Constructor using member initializer list // to initialize constVar Stu() : constVar(5) {} private: const int constVar; };
Example to Initialize const Member Variable Using Constructor
In this example, we use const to member variable say "const int x" that initialized using constructor initializer list. Next, we cannot modify the value of x after the object is constructed. Then we set one member function (getX()) to return the result.
#include<iostream> using namespace std; class Stu { // const member variable const int x; public: // initializer list to initialize const member using constructor Stu(int val) : x(val) {} // Getter to access the value of x int getX() const { return x; } }; int main() { // Create object with x Stu obj1(18); // Create another object Stu obj2(96); cout << "obj1.x = " << obj1.getX() << endl; cout << "obj2.x = " << obj2.getX() << endl; return 0; }
The above code produces the following result:
obj1.x = 18 obj2.x = 96