static class data member has
static storage, meaning a program creates only ONE copy of
a static class variable, regardless of the number of objects created. This property can be useful
when you want to share some data among several objects of the same class.
One caveat of using static class member is that you cannot initialize it inside the class
declaration, which is usually put in a header file (
.hpp). This is because the
declaration is a description of how memory is to be allocated, but it doesn’t allocate memory.
static class member is initialzed in the file containing the class methods and the scope operator
is used in the initialization to indicate to which class the static member belongs. However, one
exception is that, if the static member is a
const integral type or an enumeration type, it
can be initialized in the class declaration itself.
const static integral (or enumeration) can serve as a symbolic constant shared by all objects
of the class in which the
const static member is declared and initialzed. However, since
the constant initialization is not a definition yet, you still need to define that
in an enclosing namespace, otherwise, the linker will throw errors like ‘undefined reference to
If you are defining a constant to be shared among all the instances of the class, use static const. If the constant is specific to each instance, just use const (but note that all constructors of the class must initialise this const member variable in the initialisation list).
Let’s see some example: