Skip to content

Commit 1546043

Browse files
committed
Static Class Members
1 parent 62b155b commit 1546043

File tree

3 files changed

+85
-0
lines changed

3 files changed

+85
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#include "Player.h"
2+
3+
int Player::number_players {0} ; //initialize the static class member in the .cpp file
4+
5+
Player::Player(std::string name_val, int health_val, int xp_val)
6+
: name{name_val},health{health_val},xp{xp_val}
7+
{
8+
++number_players;
9+
}
10+
11+
Player::Player(const Player &source)
12+
:Player{source.name,source.health,source.xp}
13+
{
14+
15+
}
16+
17+
Player::~Player()
18+
{
19+
--number_players;
20+
}
21+
22+
int Player::get_number_players()
23+
{
24+
return number_players; // a static function can only see static members of the class
25+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#ifndef _PLAYER_H_
2+
#define _PLAYER_H_
3+
4+
#include <string>
5+
6+
7+
class Player
8+
{
9+
private:
10+
std::string name;
11+
int health;
12+
int xp;
13+
14+
static int number_players;
15+
16+
public:
17+
std::string get_name() { return name; }
18+
int get_health(){ return health;}
19+
int get_xp() {return xp;}
20+
21+
Player(std::string name_val,int health_val=0, int xp_val=0);
22+
Player(const Player &source);
23+
~Player();
24+
25+
static int get_number_players();
26+
27+
};
28+
29+
#endif // _PLAYER_H_
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#include <iostream>
2+
#include "Player.h"
3+
4+
using namespace std;
5+
6+
7+
void display_number_players()
8+
{
9+
cout<<"The number of players is: "<<Player::get_number_players()<<endl;
10+
}
11+
12+
int main(int argc, char **argv)
13+
{
14+
display_number_players();
15+
16+
Player george("George");
17+
display_number_players();
18+
19+
{
20+
Player kornel("Kornel");
21+
display_number_players(); //object kornel will get out of the scope as the {} block ends and gets deleted automatically because it happens on the stack
22+
}
23+
24+
display_number_players();
25+
26+
Player *ninja=new Player("Ninja", 100, 35);
27+
display_number_players();
28+
delete ninja;
29+
30+
display_number_players();
31+
}

0 commit comments

Comments
 (0)