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 and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.