Static Variable In C ++ Code Example


Example: 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 */

Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable