Static Variables Within Classes

The use of static variables can avoid the need to declare global variables. If a variable within a class is declared as static this means that a single version of that variable will be shared by all objects of that class. Further, static members are initialized to 0. Declaring a static variable doesn't mean to define it. The actual static variable definition must be made at some point further into the global area. After that, the variable exists even if no objects of the class containing it exists.

Example


#include <iostream>
#include <string>
using namespace std;

class Person
{
     static int personsNumber;   // variable declaration
     string name;
public:
     Person(string aName)
     {
           name = aName;
           personsNumber++;
     }

     ~Person()
     {
           personsNumber--;
     }

     int getPersonsNumber()
     {
           return personsNumber;
     }
};

int Person::personsNumber;     // variable definition

int main()
{   
// Person::personsNumber = 0; // If the variable were
//public, this would be ok. This statement would
                                  // be unnecessary, though,
                   //as the variable is already initialized to 0.
     Person obj1("John");
     Person obj2("Tina");
     Person obj3("Sam");
     cout << "The number of persons is: " << obj1.getPersonsNumber() << endl;
}

Output

"The number of persons is: 3"
The variable personsNumber contained in obj1 is the same that was incremented in obj2 and obj3.