Static in C++

Static Data Members

A data member of a class can be qualified as static, in which case only one instance of it exists. You would use a static data member to maintain a global value that applies to all instances of the class. Member functions can modify this value, and all other objects of the class then see the modified value. Static data members are normally used to maintain values common to the entire class. They are also known as class variables since they are associated with the class itself rather than with any class object.

Example

#include<iostream>
using namespace std;
class A

{

  static int count;

  public:

    A()

  {

    count++;

  }

  void display()

  {

    cout << "Number of objects :" << count;

  }

};

int A::count = 0; // static variable

int main()

{

  A a, b, c;

  a.display(); // prints  3

  b.display(); // prints  3

  c.display(); // prints  3

  return 0;

}

Static Member Functions

Member functions can be static. You can use static member functions to perform tasks in the name of the class or an object where the function does not need access to the members of any particular instance of the class.

Usually, you use a static member function when you need to access only the static data members of a class. Static member functions have no this pointer. A static function can have access to only other static members (static member functions or static data members) declared in the same class.

Example

#include<iostream>
using namespace std;
class A

{

  static int count;

  public:

    A()

  {

    count++;

  }

  static void display()

  {

    cout << "Number of objects : " << count;

  }

};

int A::count = 0;

int main()

{

  A a, b, c;

  A::display(); // static function,  prints  3

  return 0;

}

C++ Static Variables

A local variable with a static storage class is still a local variable as far as its scope is concerned, it is still available only inside the function in which it is declared. It gets initialized to zero automatically, is initialized only once (during program startup), and retains its value throughout the program’s execution.

When applied to a local variable, the static declaration will allow this variable to retain its value even if the function exits.

The static declaration when applied to a global variable, the global variable becomes inaccessible outside the file in which it is declared.

Leave a comment

Your email address will not be published. Required fields are marked *