Save 40% on books and eBooks + 70% on videos now through May 31*—use code PROGRAM. Shop now.
Speaking of objects with static storage, remember that you can initialize at least some types of static data members inside the class body and be rid of a separate definition of such members.
In the following class, the const static int member is declared but not initialized. The initializer appears in the definition, in a separate .cpp file:
static const int i;
const int C::i=5;
In standard C++ you can initialize static const members of integral types inside the class:
static const int i=5;
If you provide an in-class initializer, you shouldn't use a separate definition of this static member.
happens if the header file is #included
in several different translation units? Will the program have multiple copies
of C::i? No, it won't. First, remember
that this member is const, which means that the compiler can optimize it away,
and use only the literal 5 instead. Secondly, linkers nowadays are clever
enough to collapse multiple copies of the same entity (say a function template
instantiation) into one copy so you can use this technique safely.
Notice however that you can use this initialization form only with integral type. Floating point data members, strings etc. cannot use this syntax
Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.