static member

L

Lowen

It's my understanding a static member variable will be one instance among
all objects created from it, and static member functions only access static
variables. When coding, I am still not sure how to decide if to declare a
member of a class "static"? Is there some tips on this? thanks!
 
I

Ian

Lowen said:
It's my understanding a static member variable will be one instance among
all objects created from it, and static member functions only access static
variables. When coding, I am still not sure how to decide if to declare a
member of a class "static"? Is there some tips on this? thanks!
I think you have answered your own question!

If the variable is pertinent to the current instance of the class, it a
normal member, if it its value is shared by all instances of the class,
it is static.

Ian
 
J

JKop

Ian posted:
I think you have answered your own question!

If the variable is pertinent to the current instance of the class, it a
normal member, if it its value is shared by all instances of the class,
it is static.

Ian


Every dog has a unique name, every dog has a unique age. But all dog's are
of the same order "Mammal", so this is not a unique bit of info for each
individual dog:

class Dog
{
public:
char Name[15];
unsigned short int Age;

static char Order[15];
};

char Dog::Order[15] = "Mammal";


-JKop
 
P

puppet_sock

Lowen said:
It's my understanding a static member variable will be one instance among
all objects created from it, and static member functions only access static
variables. When coding, I am still not sure how to decide if to declare a
member of a class "static"? Is there some tips on this? thanks!

One of my instructors had this "trick" for deciding when to use
static and when to use non-static.

Think of the class definition as a factory, and the objects (the
instances of the class) as the cars produced in that factory.

If the information is about the car (the instance) then it should
be "per car" and a non-static member.

If the information is about the factory (the class) and not about
individual cars, then it should be static.

So, to say it another way, the static members should be information
that applies to the entire set of objects, no matter how many there
are, and the non-static should be information about inidividual
objects.

So, for example, a count of cars the factory had produced so far
would be static. The mileage on an individual car would be non-static.
Socks
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,169
Messages
2,570,919
Members
47,460
Latest member
eibafima

Latest Threads

Top