How to Declare a Static Variable in a Class in C++?
Last Updated :
15 Feb, 2024
In C++, a static variable is initialized only once and exists independently of any class objects so they can be accessed without creating an instance of the class. In this article, we will learn how to declare a static variable in a class in C++.
Static Variable in a Class in C++
To declare a static variable within a class we can use the static keyword in the definition while defining a static variable.
Syntax to Declare Static Variable in C++
To declare a static variable in a class use the below syntax:
// inside class
static dataType variableName = variableValue;
C++ Program to Declare Static Variables in a Class
The below example demonstrates how we can declare static variables in a class in C++.
C++
#include <iostream>
using namespace std;
class myClass {
public :
static int
s_value;
};
int myClass::s_value
= 1;
int main()
{
cout << "Static variable value: " << myClass::s_value
<< endl;
return 0;
}
|
Output
Static variable value: 1
Static variables belongs to the class so we do not need to create an object to access the value of the static variables.
Share your thoughts in the comments
Please Login to comment...