if you use a static variable in a class, does that mean that every object instance from that class and derived classes refer to the same variable?
Printable View
if you use a static variable in a class, does that mean that every object instance from that class and derived classes refer to the same variable?
Yes, that one static variable will hold the same value no matter from which class you access it. You don't even need to instantiate any members of that class to be able to set the value of that variable.
phew.. i was getting worried someone was gonna say no.
so whats the difference between a static variable and a global variable?
static in a class basically means global (in the scope of that class) just as static in a function means global in the scope of that function.
Static members have a few advantages over just global members. For example, you can organize your functions and variables better and group them into their related classes. For example, your color class may predefine many colors with static variables. And if you are using templates, you can access that static member with the class type name. Its always best to avoid global members, so place them in a related class if you must use them.
BTW, you can make a brand new namespace for them but if they can be placed in a class, do so.