In C++ if a member function is defined as “static” you can use it without having to create an object instance. However, inside that function you can only access public member variables that are also defined as static. Static member variable means that all instances of that class share the same instance of this variable.
The next code example will try to clarify this:
class A
{
public:
int var1;
static int var2;
void foo();
static void foo2();
};
// we can initialise var2 without creating class instance
int A::var2 = 0;
void A::foo()
{
printf(“%d”, var1);
}
void A::foo2()
{
printf(“%d”, var2);
// the next call is illegal as there is no way to tell
// which copy of var1 we are trying to access
// printf(“%d”, var1);
}
and we have the following code using class A:
A a1;
A a2;
a1.var1 = 1;
a2.var1 = 1;
a1.var2 += 2;
A::var2 += 2;
a1.var1 += 2;
// will print 3 as this is the a1’s copy of var1
a1.foo();
// will print 1 as this is the a2’s copy of var1
a2.foo();
The code for foo() is generated only ones but the C++ compiler generates additional code behind the scene that passes additional “hidden” parameter to foo() that is a pointer to the actual object instance (“this” pointer). Using that pointer the compiler automatically references the copy of var1 belonging to the object from which you call foo();
When a function is defined as “static” it does not receive that pointer. You can call this function without the need to instantiate an object, as there is no need to pass “this” pointer to it.
The following calls are doing exactly the same thing, exactly the same way:
a1.foo2();
a2.foo2();
A::foo2(); //here I specify that I am using the static member function foo2() from class A.
In all of the last tree calls it will p