Wednesday 17 February 2016

Static member function in C++

Okay, before I start the main portion of the static member function, I would like you to know that a instance (normal) function can assess both the instance member variable as well as the static member variable. So, the question the arise is that "Why do we need static member function?"

Reason for static member function :
If we want to access the private static member variable then we need a member function. Now as we know that static member variable is class member variable i.e it will occupy memory in RAM even if the object of class is not created and if we make a instance(normal) member function then we need a object to call it. Thus the significance of the static member variable will be lost because anyway we are creating an object to access the static member variable. So we need to qualify the member function with static keyword to make it static member function. And now this member function can be accessed without any object of the class.

Example :

static void setValue(float sal)
{
    salary = sal;
}

Special things about static member functions:

  • They can access only static member variables because these functions can be called without any object.
  • If object is present then we can call it in two ways:

    a1.setValue(9999999.5f); // a1 is the object of class people
    people:: setValue(999999.5f);


  • If object is not present then we need to use the second method to call the static member function.


NOTE:
The instance member function can access both the static member variable and the instance member variable.
The static member function can be called with or without objects.

1 comment: