static int vs. static function

There's something about static members I don't understand. Why can static members like int or double only be declared outside the class, not inside the class. It is legal to define a static function inside the class, why not the primitive?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

using namespace std;

class myClass2 {
public:
	//here, definition of myIntFunc is allowed
	static int myIntFunc() { return 222; } 
};

class myClass {
public:
	//static int myInt = 333;  why not allow this too???
	static int myInt; //why only declaration allowed inside class?
};

int myClass::myInt = 333; //then must define outside of class

int main() 
{
	cout << myClass2::myIntFunc() << endl;
	cout << myClass::myInt << endl;
	return 0; 
}
Actually, it's usually inadvisable to define anything inside the class. There's always (well, often) the possibility that the class is declared in more than one file. If that's the case and the class declaration also contains definitions, the linker will throw an error.

Why is this a problem, anyway?
This will do what you (apparently) want to do:

1
2
3
4
5
6
class myClass {
public:
    myClass () : i (1) {}
    ~myClass() {}
    const int i ;
} ;


And, if you really want to be able to refer to i without creating an instance of your class, you can do this:

1
2
3
4
5
6
myClass {
public:
    myClass() {}
    ~myClass() {}
    static const int i = 1 ;
} ;


and then refer to myClass::i and get 1 (or the value you prefer) as the result.

Even better would be

1
2
3
4
5
6
myClass {
public:
    myClass() {}
    ~myClass() {}
    enum {i = 1} ;
} ;


which has the same practical result when you refer to myClass::i.
Last edited on
static const int i = 333;

will work inside the class declaration and is perfectly fine since the "static" keyword guarantees there is only one copy, regardless of how many times the header gets included.
Why is this a problem, anyway?
I've seen several posts (and have made the same mistake myself) where someone declares a static inside a class and then wonders why they get a link error. They (and I) forget that it's just a declaration, NOT a definition.
Helios, you are saying (I think) if "static int myInt;" is defined inside the class, rather than just declared, and if another file uses that class, it would be a redefinition (even though identical) of that static in the global space. That makes sense, except then I don't see how the static function can be defined inside a class, since wouldn't that lead to the same redefinition problem?

CoDeReBel and jsmith thanks and I will try some test programs with static const... and the "enum" which I've never seen before. If I understand "const" it can only work as a read only variable but does not allow changing its value.

Thanks very much for all your feedback.
Topic archived. No new replies allowed.