Static objects are created only once before the program starts and destroyed when the program terminates. So they can be used to share data between different functions or instances of a class
class CountObject {
static int count; //declare share data
public:
CountObject() {
count++;
}
//static method, can be used without instantiating an object of the CountObject class
static int getCount() {
return count;
}
};
//need to define and initilize value
int CountObject::count = 0;
then we can use it like:
CountObject a, b, c;
cout<<"nums of created objects :"<<CountObject::getCount()<<endl;
Just remember to define and initialize the static object outside of the class to ensure that only one instance is created for the entire program.
int CountObject::count = 0;
Top comments (4)
That's true only of global
static
objects. Forstatic
data members as you've shown, they're initialized only before the first object of the class is created — that may be long after the program starts.you are right ! i forgot to mention about global static object and this case
And static objets inside a function are created the first time this function is called.
Yes, I know; but you never mentioned those either.