static

why doesn't this code work?
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
#include <iostream>
using namespace std;

class temp
{
private:
	static int var;
public:
	temp();
	static int lol();
};

temp::temp()
{
	var=0;
	cout<<var<<endl;
}

int temp::lol()
{
	var=5;
	cout<<var<<endl;
	return 0;
}

int main()
{
	temp::temp();
	temp::lol();
	cin.ignore();
	return 0;
}

You need to declare var;
int temp::var;
ok, but how do i have to use var then?
To declare an object: temp obj;
To use said object: obj.lol();
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
#include <iostream>
using namespace std;

class temp
{
private:
	static int var;
public:
	temp();
	static int lol();
};

temp::temp()
{
	var=0;
	cout<<var<<endl;
}

int temp::lol()
{
	var=5;
	cout<<var<<endl;
	return 0;
}

int temp::var;

int main()
{
	temp::temp();
	temp::lol();
	cin.ignore();
	return 0;
}
why do you have to do this: int temp::var; ??
Static members are declared this way.
but i have declared them here: static int var;
To quote the standard section 9.4.1:
The declaration of a static data member in its class definition is not a definition
many thanks, everybody!!
@hannes You can think of it this way if you like:

A class declaration such as:
1
2
3
4
5
6
7
8
9
class temp
{
    private:
    static int var;
      
    public:
    temp();
    static int lol();
};
is a design feature. It of itself does not generate code. It is there to tell the compiler what the class looks like.

If it worked the way that you expected - what would happen if that class was declared in a header file and that header file was #included in 10 .cpp files.
Then int var will be defined/created 10 times - this is a redefinition error.

So for static class variables it is up to you (the programmer) to define (create if you will) and initialize each class static variable once and once only somewhere outside the class block (and not in the header file - otherwise you will still have the multiple redefinition problem)

Topic archived. No new replies allowed.