
Awunjia S. answered 04/08/21
Bsc in computer science with B+ grades in C++, 2 years of experience
Hi there, to initialize a private static data member in C++, after you have declared the private static data member within the class, you use the class name and a binary scope resolution operator(::) with the variable name to assign a value without forgetting the data type. Note, this is done out of the class, not within the class, I guess that's where you are having an issue. Follow this example for a better understanding:-
#include <iostream>
using namespace std;
class Foo{
private:
static int i;
public:
Foo(){
i++; //increase the value of i when new object is created
}
static int getStaticVar() {
return i;
}
}; //Out of the Foo class
int Foo::i = 0; //initializing the private static variable i
main() {
Foo obj1, obj2, obj3; //three objects are created from Foo class
cout << "Number of objects: " << Foo::getStaticVar();
}