If you have data for a class that will be modified and needs to be retained throughout the program, but is only used in one member function, is it preferred to make that variable a local static variable of the routine that it is in or make it a member of the class?
A non-static variable can not be accessed by static member functions. A static variable acts as a global variable and is shared among all the objects of the class. A non-static variables are specific to instance object in which they are created.
Static variables are initialized to 0. It is initialized only once. Throughout the program, only one copy of the static member variable is created for the entire class hence static member variables are also called class variables. It is shared by all instances of the class.
A local variable is the variable you declare in a function. Its lifespan is on that Function only. A member variable is the variable you declare in a class definition. Its lifespan is inside that class only.It is Global Variable.It can be access by any function inside that same class.
Demo Program An instance data member of a class is recreated each time when a new instance of the class is created and it is associated with that instance only. Whereas a static data member of a class is not recreated with new instance creation, only one copy of it is shared by all the instances.
The question isn't "will the data be used throughout the program", but rather "if you make two objects of this class, do you want them to share this data?" If yes, make it static. If no, don't.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With