I know the code below is faulty (actually I have made it so!). I just wanted to know how the stat variable of a class is to be defined/initialized outside the class. I believe I can get away with the keyword unsigned const static because they doesn't define the type of the variable rather they are simply modifiers (just like adjectives).
Should it be written as :
int foo::count = 0;or,
[COLOR="#40E0D0"]unsigned const static[/COLOR] int count = 0;?
// statdata.cpp
// static class data
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
class foo
{
private:
unsigned const static int count; //only one data item for all objects
//note: *declaration* only!
public:
foo() //increments count when object created
{ count++; }
int getcount() //returns count
{ return count; }
};
//--------------------------------------------------------------
[B][COLOR="#FF8C00"]int foo::count = 0;[/COLOR][/B] //*definition* of count
////////////////////////////////////////////////////////////////
int main()
{
foo f1, f2, f3; //create three objects
cout << "count is " << f1.getcount() << endl; //each object
cout << "count is " << f2.getcount() << endl; //sees the
cout << "count is " << f3.getcount() << endl; //same value
return 0;
}


Sign In
Create Account


Back to top









