When i run the code(first program) ,it shows a error that var is private member.I defined it is a static member so shouldn't be var initilized outside of the class.
#include <iostream>
using namespace std;
class example{
private:
static int var;
public:
example(){
cout<< "exp is called"<< endl;
};
};
int example::var =6;
int main(void)
{
example exp1;
cout<< exp1.var<<endl;
exp1.var=5;
example exp2;
cout<< exp2.var<<endl;
cout<< example::var<<endl;
return 0;
}
but this code works succesfully;
#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;
}
};
int MyClass::st_var = 0; //initializing the static int
main() {
MyClass ob1, ob2, ob3; //three objects are created
cout << "Number of objects: " << MyClass::getStaticVar();
}
What's wrong in the code(first program)?