DEV Community

dinhluanbmt
dinhluanbmt

Posted on

C++, Static Object - share data

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;
Enter fullscreen mode Exit fullscreen mode

then we can use it like:

CountObject a, b, c;
cout<<"nums of created objects :"<<CountObject::getCount()<<endl;
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
pauljlucas profile image
Paul J. Lucas

Static objects are created only once before the program starts and destroyed when the program terminates.

That's true only of global static objects. For static 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.

Collapse
 
dinhluanbmt profile image
dinhluanbmt

you are right ! i forgot to mention about global static object and this case

Collapse
 
pgradot profile image
Pierre Gradot

And static objets inside a function are created the first time this function is called.

Collapse
 
pauljlucas profile image
Paul J. Lucas

Yes, I know; but you never mentioned those either.