
- 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
Static Data Member Initialization in C++
Here we will see how to initialize the static member variables initialization in C++. We can put static members (Functions or Variables) in C++ classes. For the static variables, we have to initialize them after defining the class.
To initialize we have to use the class name then scope resolution operator, then the variable name. Now we can assign some value.
The following code will illustrate the of static member initializing technique.
Example
#include <iostream> using namespace std; class MyClass{ private: static int st_var; public: MyClass() { st_var++; //increase the value of st_var when new object is created } static int getStaticVar() { return st_var; } }; int MyClass::st_var = 0; //initializing the static int main() { MyClass ob1, ob2, ob3; //three objects are created cout << "Number of objects: " << MyClass::getStaticVar(); }
Output
Number of objects: 3
- Related Articles
- C++ static member variables and their initialization
- Initialization of static variables in C
- A static initialization block in Java
- A non-static initialization block in Java
- What are static member functions in C#?
- Initialization of global and static variables in C
- How static variables in member functions work in C++?
- Count the number of objects using Static member function in C++
- Why interfaces don't have static initialization block when it can have static methods alone in java?
- Count the number of objects using Static member function in C++ Program
- Why Java wouldn't allow initialization of static final variable in a constructor?
- Static Data Members in C++
- Static Finger Theorem in Data Structure
- Parent and Child classes having same data member in Java
- How do I create static class data and static class methods in Python?

Advertisements