How to initialise static variable in C++

In this tutorial, we will learn how we will be initializing the static variable in C++. First, let us understand how to declare them?

For a Detailed study go to the link Initialization of private static members in C++

HOW STATIC MEMBERS ARE DECLARED in C++

These static variables are the type of members that are deployed by using static keywords in C++ Classes. Given the syntax below

SYNTAX :      static data_type data_member_name;

 

To Have a Better and easy solution to the problem let us discuss the approach which we are going to take towards the question.

APPROACH

We can put every static member whether it is a function or it is a variable in C++ Classes. For putting the static variables, we have to first initialize them after defining the C++ class. For initializing it is required to use the name of the class which must be followed by the scope resolution operator (::) and after that the name of the static variable.

FOR EXAMPLE:             Class::StaticVariable()


Now we can assign them some value.

C++ Program to initialize the static variable

#include <iostream>

using namespace std;

//INITALIZING THE CLASS 
class staticvar{
   private:
      static int st_var;
   public:
      
     staticvar(){
         st_var++; //increase the value of st_var when new object is created
      }
      static int getStaticVar() {
         return st_var;
      }
};

int staticvar::st_var = 0; //initializing the static int as a global variable

//Main function
void main() {
   staticvar ob1,ob2; //object is created
   cout << "Number of objects: " << staticvar::getStaticVar();
}

 

OUTPUT:

Number of objects:2

Leave a Reply

Your email address will not be published.