static variable c++ class 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 class in C++
#include <iostream>
using namespace std;
class Box {
public:
static int objectCount;
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
objectCount++;
}
double Volume() {
return length * breadth * height;
}
private:
double length;
double breadth;
double height;
};
int Box::objectCount = 0;
int main(void) {
Box Box1(3.3, 1.2, 1.5);
Box Box2(8.5, 6.0, 2.0);
cout << "Total objects: " << Box::objectCount << endl;
return 0;
}