How to Declare a Static Data Member in a Class in C++?
Last Updated :
22 Feb, 2024
Improve
In C++, when we declare a member as static, then it means that the member will have only one copy that is shared by all objects of that class and we don't need any object to access that member In this article, we will learn how to declare a static data member in a class in C++.
Declaring Static Data Member in a Class in C++
To declare a static member within a class we can use the static keyword in the definition while defining a static member inside a class.
Syntax to Declare Static Member in C++
//inside class
static dataType dataMemberName;
Static data members must be initialized outside the class definition.
C++ Program to Declare a Static Member in a Class
The below example demonstrates how we can declare and access the static members in a class in C++.
// C++ program to declare static member in a class
#include <iostream>
using namespace std;
class MyClass {
public:
static int
staticVar; // Declaring static member variable
static void staticFunc()
{ // Declaring and defining static member function
cout << "Value of static variable: " << staticVar
<< endl;
}
};
// Defining and initializing static member variable
int MyClass::staticVar = 0;
int main()
{
// Accessing static member variable without creating an
// instance of MyClass
MyClass::staticVar = 10;
// Calling a static member function without creating an
// instance of MyClass
MyClass::staticFunc();
return 0;
}
Output
Value of static variable: 10
Note: Static members belongs to the class so we do not need to create an object to access the value of the static members.