Wednesday, February 29, 2012

How to initialize const variable in C++?

In C++, const keyword is used to create the one time initializer and read-only variable. Once intialised, it is not legal to change the value later. There are two ways to initiaze the const varaibles in C++.
class cns
    const int val; // declaring const variable
    const static int st=10;   //declaring n initializing using static keyword
    cns(int aa = 0) :val(aa) // initializing using initialization list
    cns con(10);

P.S: if const variables are not initialised, the values are undefined and it will not allow to change the values. So it is mandatory to initialize the const variables.

No comments:

Popular Posts