1/*
2this example show where and how
3static variables are used
4*/
5
6#include <iostream>
7#include <string>
8
9//doing "using namespace std" is generally a bad practice, this is an exception
10using namespace std;
11
12class Player
13{
14 int health = 200;
15 string name = "Name";
16
17 //static keyword
18 static int count = 0;
19public:
20 //constructor
21 Player(string set_name)
22 :name{set_name}
23 {
24 count++;
25 }
26
27 //destructor
28 ~Player()
29 {
30 count--;
31 }
32
33 int how_many_player_are_there()
34 {
35 return count;
36 }
37
38};
39
40int main()
41{
42 Player* a = new Player("some name");
43 cout << "Player count: " << *a.how_many_player_are_there() << std::endl;
44
45 Player* b = new Player("some name");
46 cout << "Player count: " << *a.how_many_player_are_there() << std::endl;
47
48 delete a;
49
50 cout << "Player count: " << *b.how_many_player_are_there() << std::endl;
51}
52
53/*output:
541
552
561
57*/
1#include<iostream>
2//Singleton class is a class having only one instance
3class SingleTon {
4
5public:
6 static SingleTon& Get() {
7 static SingleTon s_Instance;
8 return s_Instance;
9 }//there is only one instance of static functions and variables across all instances of class
10 void Hellow() {}
11};
12void Increment() {
13 int i = 0;//The life time of variable is limited to the function scope
14 i++;
15 std::cout << i << std::endl;
16};//This will increment i to one and when it will reach the end bracket the lifetime of var will get destroyed
17void IncrementStaticVar() {
18 static int i = 0;//The life time of this var is = to program
19 i++;
20 std::cout << i << std::endl;
21}//This will increment i till the program ends
22int main() {
23
24 Increment();//output 1
25 Increment();//output 1
26 Increment();//output 1
27 IncrementStaticVar();// output 2
28 IncrementStaticVar();// output 3
29 IncrementStaticVar();// output 4
30 IncrementStaticVar();// output 5
31 SingleTon::Get();
32 std::cin.get();
33
34}