what is a static variable in c++ code example
Example 1: static variable in c++
#include <iostream>
#include <string>
using namespace std;
class Player
{
int health = 200;
string name = "Name";
static int count = 0;
public:
Player(string set_name)
:name{set_name}
{
count++;
}
~Player()
{
count--;
}
int how_many_player_are_there()
{
return count;
}
};
int main()
{
Player* a = new Player("some name");
cout << "Player count: " << *a.how_many_player_are_there() << std::endl;
Player* b = new Player("some name");
cout << "Player count: " << *a.how_many_player_are_there() << std::endl;
delete a;
cout << "Player count: " << *b.how_many_player_are_there() << std::endl;
}
Example 2: static inside local scope in c++
#include<iostream>
class SingleTon {
public:
static SingleTon& Get() {
static SingleTon s_Instance;
return s_Instance;
}
void Hellow() {}
};
void Increment() {
int i = 0;
i++;
std::cout << i << std::endl;
};
void IncrementStaticVar() {
static int i = 0;
i++;
std::cout << i << std::endl;
}
int main() {
Increment();
Increment();
Increment();
IncrementStaticVar();
IncrementStaticVar();
IncrementStaticVar();
IncrementStaticVar();
SingleTon::Get();
std::cin.get();
}
Example 3: static in class c++
#include <iostream>
class Entity {
public:
static int x,y;
static void Print() {
std::cout << x << ", " << y << std::endl;
}
};
int Entity:: x;
int Entity:: y;
int main() {
Entity e;
Entity e1;
e.x = 5;
e.y = 6;
e1.x = 10;
e1.y = 10;
e.Print();
e1.Print();
Entity::x;
Entity::Print();
std::cin.get();
}