Const keyword

Const keyword is used to make any element of a program constant. Let's see its significance with different program elements.

Const Variables

If we declare a variable as const, we cannot change its value. A const variable must be assigned a value at the time of its declaration.

Once initialized, if we try to change its value, then we will get compilation error. The following two cases will give us an error since in both these cases, we are trying to change the value of a const variable.

intmain(){constinta=5;// declaring and initializing a const variablea=10;// this will give compilation errorreturn0;}

intmain(){constinta=5;// declaring and initializing a const variablea++;// this will give compilation errorreturn0;}

Const Function Parameters and Return type

We can also make the type of argument and return type of a function const. Once declared constant, we will get compilation error if we try to change it.

voidfunc(constinta)// const argument{a=5;// compilation error}

This will result in compilation error since we cannot assign a value to any const variable after its declaration. Initialization of any const variable (in our case, a) takes place at the time of its declaration.

The above program will give compilation error. Since we declared 'a' as a const object of class A, we cannot change its data members. When we created 'a', its constructor got called assigning a value 0 to its data member 'x'. Since 'x' is a data member of a const object, we cannot change its value further in the program. So when we tried to change its value, we got compilation error.

Constant Member Function of Class

A const member function cannot change the value of any data member of the class and cannot call any member function which is not constant.

To make any member function const, we add the const keyword after the list of the parameters after the function name.

classA{public:intx;voidfunc()const{x=0;// this will give compilation error}};

The above code will give us compilation error because 'func()' is a const member function of class A and we are trying to assign a value to its data member 'x'.

A const object can only call a const member function.

This is because a const object cannot change the value of the data members and a const member function also cannot change the value of the data member of its class. So, a const object would like to call a function which does not violate its rule.

We cannot make constructors const

The reason for this is that const objects initialize the values of their data members through constructors and if we make the constructor const, then the constructor would not change the values of the data members and the object would remain uninitialized.