- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ static member variables and their initialization
Static C++ member variables are defined using the static keyword. The static member variables in a class are shared by all the class objects as there is only one copy of them in the memory, regardless of the number of objects of the class.
The static class member variables are initialized to zero when the first object of the class is created if they are not initialized in any other way.
A program that demonstrates static member variables and their initialization in C++ is given as follows.
Example
#include <iostream> using namespace std; class Demo { public : static int num; int display() { cout << "The value of the static member variable num is: " << num; } }; int Demo::num = 100; int main() { Demo obj; obj.display(); return 0; }
Output
The output of the above program is as follows.
The value of the static member variable num is: 100
Now let us understand the above program.
In the class Demo, the static class member variable is num. The function display() prints the value of num. The code snippet that shows this is as follows.
class Demo { public : static int num; int display() { cout << "The value of the static member variable num is: " << num; } }; int Demo::num = 100;
In the function main(), an object obj of class Demo is created. Then the function display() is called that displays the value of num. The code snippet that shows this is as follows.
int main() { Demo obj; obj.display(); return 0; }
- Related Articles
- Static Data Member Initialization in C++
- Initialization of static variables in C
- Initialization of global and static variables in C
- How static variables in member functions work in C++?
- Why are global and static variables initialized to their default values in C/C++?
- Class and Static Variables in C#
- Templates and Static variables in C++
- What are static member functions in C#?
- Static Variables in C
- Member variables in Java
- Member variables vs Local variables in Java
- A static initialization block in Java
- Kotlin static methods and variables
- A non-static initialization block in Java
- Static and non static blank final variables in Java
