C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » C++ programming language

Initialization of class's const data member in C++

A const data member cannot be initialized at the time of declaration or within the member function definition.

To initialize a const data member of a class, follow given syntax:

Declaration

const data_type constant_member_name;

Initialization

class_name(): constant_member_name(value)
{
}

Let's consider the following example/program

#include <iostream>
using namespace std;

class Number
{
	private:
		const int x;
	public:
		//const initialization
		Number():x(36){}
		//print function
		void display()
		{cout<<"x="<<x<<endl;}
};
int main()
{
	Number NUM;
	NUM.display();
	
	return 0;
}
    x=36





In this program, Number is a class and x is a constant integer data member, we are initializing it with 36.

Here,

Declaration of const data member is:

const int x;

Initialization of const data member is:

Number():x(36){}

COMMENTS