ADVERTISEMENT
ADVERTISEMENT

C++ - Declare Constant Variable inside C++ Class.


IncludeHelp 19 August 2016

In this example we will learn how to declare constant data member inside class declaration in c++ programming language.

While declaring a constant variable we need to initialize a value but in c++ class we can initialize value to constant variable.

In this example you will learn to declare and then initialize constant data member inside class.

Follow these two steps:

  1. Declare data member in private section (If required)
  2. const int a;
  3. Assign value in using following syntax
  4. class_name() : variable_name(value_to_initialize){}

C++ Code Snippet - Declare Constant Member (Variable) inside C++ Class

/*C++ - Declare Constant Variable inside C++ Class.*/

#include <iostream>

using namespace std;

class Example{
	private:
		//declaration of constant variable
		const int a;
		int b;
	public:
	    //assign value to const int a
	    Example():a(10){}
	    
		void assignValue(void){
			b=20;
		}
		void printValue(void){
			cout<<"a: "<<a<<endl;
			cout<<"b: "<<b<<endl;
		}
};

int main(){
	
	//declare object
	Example Ex;
	
	Ex.assignValue();
	Ex.printValue();
	
	return 0;
}
    a: 10
    b: 20

ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

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.