Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static variable vs. member

Tags:

c++

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?

like image 813
Anonymous Avatar asked Nov 07 '09 22:11

Anonymous


People also ask

Is static variable same as static member?

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.

What is a static member variable?

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.

What is the difference between member and variable?

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.

What is the difference between static and instance members?

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.


1 Answers

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.

like image 139
David Seiler Avatar answered Sep 30 '22 02:09

David Seiler