Trying to understand static members

Quick question, why does the compiler say "undefined reference" when I do something like this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 //snippet of stack.h
class stack
{
	static double runningtotal;
	enum{max = 10};
	item items[10];
	int top;
public:
	stack();
	bool pop(item & theitem);
	bool push(item & theitem);
	bool isfull();
	bool isempty();
};
//snippet of stack.cpp
bool stack::pop(item & theitem)
{
	if (isempty())
		return false;
	else
	{
		top--;
/* ----> */	stack::runningtotal += theitem.payment;
	}
	return true;
}
C++ is weird.

Static members do not get "instantiated" by their declaration line. I still don't fully understand why.

To instantiate it, you need to put this in stack.cpp (just near the top somewhere, after stack.h is included):

 
double stack::runningtotal;
Thanks Disch, worked like a charm.
Disch wrote:
Static members do not get "instantiated" by their declaration line. I still don't fully understand why.
Because the header file gets included by multiple source files, and it would cause linker errors?
Yeah I get that it's externally linked similarly to how you have to declare globals as externally linked. I guess I just think that's a oddity of the language.
Thinking that linkage is weird (I do too) is entirely different from thinking what I thought you were thinking ;)

Hopefully when we finally get Modules this whole mess will clean itself up.
Last edited on
Topic archived. No new replies allowed.