How to initialize const member variable in a C++ class?

Here we will see how to initialize the const type member variable using constructor?

To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma.


#include <iostream>
using namespace std;
class MyClass{
      const int x;
      MyClass(int a) : x(a){
   void show_x(){
      cout << "Value of constant x: " << x ;
int main() {
   MyClass ob1(40);


Value of constant x: 40

Updated on: 30-Jul-2019

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started