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



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.