initializing static variable

I was first introduced to keyword static when going over singleton classes and then saw it again when trying to prevent a class from instantiating on the stack.

Now I am trying to simply initialize a static variable, and after many trials I could not seem to do it inside the class unless it was a const. I could not do it in the main() either and the only place I can seem to be able to do it is outside the class & outside main().

When I think about it, it kind of makes sense that initialization is blocked otherwise it may initialize the static member over and over again upon instantiation of each object. Is this set in stone, or is there another way to initialize?


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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <iostream>

using namespace std;

class Test
{
public:
	static int counter;		
	//static int counter = 1;	//Cannot do
	
	static const int counter2 = 1;

	//Test(): counter(1)		//Cannot do
	Test()
	{		
		cout << counter << endl;
		++counter;
	}
	
	void SetInitialize()
	{
		//counter = 1;			//Cannot do as initializer
	}
	
	void IncreaseByOne()
	{
		cout << counter << endl;
		++counter;
	}
};

int Test::counter = 1;

int main()
{
	//Test::counter = 1;		//Cannot do
	Test test1;
	//test1.counter = 1;		//Cannot do as initializer
	
	//test1.SetInitialize();	//Cannot do as initializer
	
	test1.IncreaseByOne();
	test1.IncreaseByOne();
	test1.IncreaseByOne();
	test1.IncreaseByOne();
	test1.IncreaseByOne();
	
	
	
	return 0;
}
The reason is that variables are normally only allowed be defined once. Class definitions are normally put in header files so if the static variable inside the class definition was a variable definition it would lead to multiple definitions because it would get defined in each translation unit where it is included. That's why it's only a declaration so you can define it outside the class in a .cpp file where it only gets defined once.

That said, C++17 introduced inline variables which, like inline functions, are allowed to be defined multiple times (in different translation units, assuming they are the same). This makes it possible to define static variables directly inside the class definition.

1
2
3
4
5
6
class Test
{
public:
	static inline int counter = 1; 
	...
};
Last edited on
Topic archived. No new replies allowed.