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++.
- Using initialisation list
- Using static keyword
class cns { private: const int val; // declaring const variable const static int st=10; //declaring n initializing using static keyword public: cns(int aa = 0) :val(aa) // initializing using initialization list { } }; main() { 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:
Post a Comment