
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
#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; }
- Related Articles
- What are static member functions in C#?
- C++ static member variables and their initialization
- Member variables in Java
- Member variables vs Local variables in Java
- Const member functions in C++
- Static Data Member Initialization in C++
- Static Variables in C
- Static variables in Java
- Static functions in C
- How to Use Static Variables in Arduino?
- How to use Static Variables in JavaScript?
- Final static variables in Java
- Static and non static blank final variables in Java
- How does Static Electricity Work?
- Initialization of static variables in C
