Contents|Index|Previous|Next
Declare
and define static members
When a class has static
data members, it is not enough to declare the static member; you
must also define it. Use the following example, for instance.
class Foo
{
: : :
void method();
static int bar;
};
This declaration only establishes
that the class Foo
has an int
named Foo::bar,
and a member function named Foo::method.
But you still need to define both method
and bar
elsewhere. According to the draft ANSI standard, you must supply an initializer
in one (and only one) source file, such as the following example shows.
int Foo::bar = 0;
Other C++ compilers may not
correctly implement the standard behavior. As a result, when you switch
to g++
from one of these compilers, you may discover that a program that appeared
to work correctly in fact does not conform to the standard: g++
reports as undefined symbols any static data members that lack definitions.