explaination of static in layman's language

closed account (1vf9z8AR)
I looked up everywhere but really can't understand how static works.Can you tell me its overview in layman's language. Not too much explaination just a little bit with the syntax(most simple).

Thankyou for your time:)
The static keyword has many uses in C++.

static local variables
If you declare a variable as static inside a function it means the variable will be created and initialized the first time the function is called and will stay alive for the rest of the function. Next time the function is called variable will have the value that it after the last time the function was called.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

int count()
{
	static int count = 0; // The variable is initialized to zero the 
	                      // first time the function is called.

	++count; // The variable is incremented each
	         // time the function is called.

	return count;
}

 
int main()
{
	std::cout << count() << '\n'; // 1
	std::cout << count() << '\n'; // 2
	std::cout << count() << '\n'; // 3
}


static class members
Normally each object of a class gets its own copy of the data members (variables), but if you declare a data member as static it will be shared by all objects. To call a static member function you don't need an object of the class.

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
#include <iostream>

class A
{
public:
	A();
	A(const A&) = delete;
	~A();
	static int getNumberOfInstances();
private:
	static int numberOfInstances;
	
};

int A::numberOfInstances = 0;

A::A()
{
	++numberOfInstances;
}

A::~A()
{
	--numberOfInstances;
}

int A::getNumberOfInstances()
{
	return numberOfInstances;
}

 
int main()
{
	A a;
	A b;
	std::cout << A::getNumberOfInstances() << '\n'; // 2
}


internal linkage
Declaring a global variable or function as static means the it will have internal linkage, i.e. it will not be accessible from other source files.

A.cpp
1
2
3
4
5
6
#include <iostream>

static void hello()
{
	std::cout << "Hello!\n";
}

B.cpp
1
2
3
4
5
6
7
void hello();
 
int main()
{
	hello(); // Linking error... Would have worked fine if the
	         // function had not been defined as static in A.cpp.
}
Last edited on
Topic archived. No new replies allowed.