How static variables in member functions work in C++?


The static variables in member functions are declared using the keyword static. The space for the static variables is allocated only one time and this is used for the entirety of the program. Also, there is only one copy of these static variables in the whole program.

A program that demonstrates static variables in member functions in C++ is given as follows.

Example

 Live Demo

#include <iostream>
using namespace std;
class Base {
   public :
   int func() {
      static int a;
      static int b = 12;
      cout << "The default value of static variable a is: " << a;
      cout << "\nThe value of static variable b is: " << b;
   }
};
int main() {
   Base b;
   b.func();
   return 0;
}

Output

The output of the above program is as follows.

The default value of static variable a is: 0
The value of static variable b is: 12

Now let us understand the above program.

The member function func() in class Base contains two static variables a and b. The default value of a is 0 and the value of b is12. Then these values are displayed. The code snippet that shows this is as follows.

class Base {
   public :
   int func() {
      static int a;
      static int b = 12;
      cout << "The default value of static variable a is: " << a;
      cout << "\nThe value of static variable b is: " << b;
   }
};

In the main() function, an object b of class Base is created. Then the function func() is called. The code snippet that shows this is as follows.

int main() {
   Base b;
   b.func();
   return 0;
}

Updated on: 26-Jun-2020

775 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements