I am new to C++.
I have a class like this:
class CodeTest
{
private:
static const int TOTAL=100;
};
Is TOTAL
a dec
Since this stirred up some controversy, I looked in the standard, and @Nawaz is right, I was wrong.
9.4.2/2
If a
static
data member is of const integral type [...]. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.
So what you have there is a declaration, and the variable is initialized to a value. Outside the class you must define the variable, but not assign a value to it.
The part with const
integral type only applies to this particular case - i.e. you can initialize said type inside the class, but all static
data members must be defined outside.
Regardless of whether the definition is or isn't required outside the class (depending on whether you use the member or not), whatever is inside the class (initialized or not) is just a declaration.
static const int TOTAL=100; // is a declaration followed by an initialisation.
From the C++ standard section 3.1:
A declaration introduces names into a translation unit or redeclares names introduced by previous declarations. A declaration specifies the interpretation and attributes of these names.
The next paragraph states that a declaration is a definition unless...... it declares a static member within a class definition:
struct X
{
int a; // defines a
static int b; // declares b
};
You can read more about definition and declaration here: SO: What is the difference between a definition and a declaration?
The declaration in an implementation file outside of the header is required because otherwise every translation unit that includes this header would define its own object (that is, its own storage for the variable).
This would violate the One Definition Rule. A consequence would be e.g. that if the variable was changed in one translation unit, this change would be invisible to other translation units. Now, this isn’t that relevant since the variable is constant. However, taking its address would also yield different pointers in different translation units.
First part of the question:
This line: static const int TOTAL=100;
is a declaration followed by an initialisation.
TOTAL
is an identifier.
Second part of the question
const int CodeTest::TOTAL
is required to initialize the variable.