Open In App

How to Declare a Static Variable in a Class in C++?

Last Updated : 15 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program  to declare static variable value
#include <iostream>
using namespace std;
class myClass {
public:
    static int
        s_value; // declaring the static member variable
};
  
int myClass::s_value
    = 1; // defining the static member variable
  
int main()
{
    // can directly access the static variable through class
    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.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads