
- 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
When are static C++ class members initialized?
Static C++ class members can be defined using the static keyword. The static member in a class is shared by all the class objects as there is only one copy of the static class member in the memory, regardless of the number of objects of the class.
The static class member is initialized to zero when the first object of the class is created if it is not initialized in any other way.
A program that demonstrates static class members in C++ is given as follows.
Example
#include <iostream> using namespace std; class Example { public : static int a; int func() { cout << "The value of static member a: " << a; } }; int Example::a = 20; int main() { Example obj; obj.func(); return 0; }
Output
The output of the above program is as follows.
The value of static member a: 20
Now let us understand the above program.
In the class Example, the static class member is a. The function func() displays the value of a. The code snippet that shows this is as follows.
class Example { public : static int a; int func() { cout << "The value of static member a: " << a; } }; int Example::a = 20;
In the function main(), an object obj of class Example is created. Then the function func() is called that displays the value of a. The code snippet that shows this is as follows.
int main() { Example obj; obj.func(); return 0; }
- Related Articles
- What are static members of a C# Class?
- What are static members of a Java class?
- When do function-level static variables get initialized in C/C++?
- Static Data Members in C++
- Defining static members in C++
- What are the steps to read static members in a Java class?\n
- Why are global and static variables initialized to their default values in C/C++?
- What are the differences between class methods and class members in C#?
- How to initialize private static members in C++?
- Static Members in Ruby Programming
- When are static objects destroyed in C++?
- Static class in C#
- What are the differences between a static and a non-static class in C#?
- Accessing protected members in a C++ derived class
- Do static variables get initialized in a default constructor in java?
