Lesson 8 | Static members of a class |
Objective | Explore the use of static members in a class. |
C++ Static Members of Class
Data members of a class can be declared with the storage class modifier static
.
A data member that is declared static
is shared by all variables of that class and is stored in only one place.
Nonstatic data members are created for each instance of the class. Since a static member is independent of an particular instance,
it can be accessed in the form (see below). [*]
[*]
class name ::
identifier
A static member of a global class must be explicitly declared and defined in file scope.
Let us look at an example:
class str {
public:
static int how_many; //declaration
void print();
void assign(const char*);
.....
private: //implement fixed length char array
char s[100];
};
int str::how_many = 0; //definition and init
In our example, how_many
could track how much memory is being used to store str
variables. Therefore:
str s1, s2, s3, *p;
str::how_many = 3;
.....
str t;
t.how_many++; //dot operator to access
.....
p = new str;
p -> how_many++; //pointer operator to access
.....
delete p;
str::how_many--;