const variable in c++ class
The const variable specifies whether a variable is modifiable or not. The constant value assigned will be used each time the variable is referenced. The value assigned cannot be modified during program execution. class is typically declared in a header file and a header file is typically included into many translation units. However, to avoid complicated linker rules, C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects. A const variable has to be declared within the class, but it cannot be defined in it. We need to define the const variable outside the class.
Header file first
class A { public: static const int ab=10; };
Main file
#include<iostream> #include "head.h" using namespace std; int main() { cout<<A::ab; getchar(); return 0; }
Example (in single file)
#include<iostream> using namespace std; class A { public: static const int ab=10; }; int main() { cout<<A::ab; getchar(); return 0; }
But this is not good convention.