
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Static Variables in Member Functions 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
#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; }