Wednesday 17 February 2016

Static member function in C++

There are two types of member variables in a class in C++.

  • Instance member variable - belongs to the instance(object) of the class.
  • Static member variable - belongs to the whole class.


Here we will study about the static member variable.
Key points:

  • Declared (but not initialized) inside the class body.
  • Also known as the class member variable.
  • They must be defined (or initialized) outside the class.
  • Static member variable does not belong to any particular object, but to the whole of the class.
  • There will be only one copy of static member variable.
  • Any object can use the same copy of static member variable or the class variable.


Explanation :
Meaning of static member variable is " declaration of a variable qualified with static keyword into a class".
Example:

class people
{
  private:
    int a;
    static float salary;
  public:
    void setSalary(int b)
    { a = b; }
};

Now in main if we make an object of the class people like.
void main()
{
  people a1;
}

'a1' is an object in which there will be only one variable 'a' and 'salary' variable is not a part of the object a1.
Even is I don't make any object to the class then also othe 'salary' variable exists.

Important Notes:

  • In C++ if we just declare the static variable into the class then that variable does not get any memory.
  • We need to write the defination of the static member variable then only static variable will get memory.
  • The definition of static member variable has to be written outside the class.
  • eg. of definition is :- float people:: salary = 9999999.5f;
  • If we want to use the static member variable in any other functio then we can use it with help of membership label (class name and scope resolution)
  • It we want to use the static member variable through an object then also we can use it normally as we use other instance member variable of class. But same memory will be used for all the objects.
  • Note that if static member variable is private then we can not access it directly outside the class and thus to access this we need to make a member function which has to be a static member function.


For more details visit here.

1 comment: