#include <iostream>
using namespace std;
class Box
{
public:
static int objectCount;
}
// Initialize static member of class Box
int Box::objectCount = 0;
Asked
Active
Viewed 3,093 times
3

Paul Beckingham
- 14,495
- 5
- 33
- 67

Rahul Sonanis
- 55
- 2
- 7
-
Primitive types like `int` actually _can be_ initialized at the point of declaration of `static` class members. – πάντα ῥεῖ Feb 07 '15 at 12:15
-
That was an omission on the part of earlier C++ standard, which has been fixed in a later edition of the standard. – Sergey Kalinichenko Feb 07 '15 at 12:19
-
3Huh? To counter the earlier comments, GCC rejects in-class initialisation with "error: ISO C++ forbids in-class initialization of non-const static member", and clang does with "error: non-const static data member must be initialized out of line". Both regardless of `-std=*` options. Which standard supposedly allows this? – Feb 07 '15 at 12:29
1 Answers
3
It seems that you mix up the declaration and the definition of a variable.
The declaration just tells the compiler a name. So in your case:
class Box
{
public:
static int objectCount;
};
This just tells the compiler that there is a variable with the name objectCount
.
But now you still need a definition.
int Box::objectCount = 0;
Simplified the definition is what the linker needs.
So as a simple rule static member variables must be declared in the class and then defined outside of it.

mkaes
- 13,781
- 10
- 52
- 72