c++ initialize static variable
// in c++ static variables can only be initalized at run time
c++ initialize static variable
// in c++ static variables can only be initalized at run time
static variable in c++
/*
this example show where and how
static variables are used
*/
#include <iostream>
#include <string>
//doing "using namespace std" is generally a bad practice, this is an exception
using namespace std;
class Player
{
int health = 200;
string name = "Name";
//static keyword
static int count = 0;
public:
//constructor
Player(string set_name)
:name{set_name}
{
count++;
}
//destructor
~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;
}
/*output:
1
2
1
*/
static variable in c++
#include<iostream>
//Singleton class is a class having only one instance
class SingleTon {
public:
static SingleTon& Get() {
static SingleTon s_Instance;
return s_Instance;
}//there is only one instance of static functions and variables across all instances of class
void Hellow() {}
};
void Increment() {
int i = 0;//The life time of variable is limited to the function scope
i++;
std::cout << i << std::endl;
};//This will increment i to one and when it will reach the end bracket the lifetime of var will get destroyed
void IncrementStaticVar() {
static int i = 0;//The life time of this var is = to program
i++;
std::cout << i << std::endl;
}//This will increment i till the program ends
int main() {
Increment();//output 1
Increment();//output 1
Increment();//output 1
IncrementStaticVar();// output 2
IncrementStaticVar();// output 3
IncrementStaticVar();// output 4
IncrementStaticVar();// output 5
SingleTon::Get();
std::cin.get();
}
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us