1. Static Variable of Class Member
Static member variables are just like static variable that we saw in the previous blog. The only way it differs is it can be accessed through the scope resolution operator [::] using the class name in which it is declared.
The
lifetime is same as the normal static variable. One more important point! There
will be only one copy of the static member and it does not matter how many
instance you create.
class StaticMemberTest
{
public:
StaticMemberTest();
~StaticMemberTest();
static int
TotalInstance;
};
In the
above code, the static member is kept in the class StaticMemberTest. You
can access the static member using the class and scope resolution operator as
shown below:
StaticMemberTest::TotalInstance
Or you
can access it using the object of the class. All the objects of the class StaticMemberTest will share the single copy of the static member.
2. Initializing the member
As we know the static member comes alive when the program starts, it needs to be initialized even before the object of the containing class gets created. To do that after the class definition, the static member should be initialized. Consider the above piece of code; the member can be initialized as shown below:
//Initializing the
static member of a class
int StaticMemberTest::TotalInstance =
0;
3. The example
1) First a class is created with a static member in it.
// CPPTST.cpp : Defines
the entry point for the console application.
//
#include "stdafx.h"
#include <conio.h>
//Class Having static
Member
class StaticMemberTest
{
public:
StaticMemberTest();
~StaticMemberTest();
static int
TotalInstance;
};

Join the conversation! Your thoughts help the community grow.