Answers for "How do you initialize a private static data member in C++?"

C++
1

How do you initialize a private static data member in C++?

#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;
      }
};

// don't forget the type of the variable you want to initialize
int MyClass::st_var = 0; //initializing the static int

main() {
   MyClass ob1, ob2, ob3; //three objects are created
   cout << "Number of objects: " << MyClass::getStaticVar();
}
Posted by: Guest on April-02-2021

Code answers related to "How do you initialize a private static data member in C++?"

Browse Popular Code Answers by Language