Static Vars in member-functions?

M

Martin T.

Hello.

Is a static Variable in a member function of a class static with regard
to one object, or is it static for all objects of the class?

That is:
Code:
class A {
// ...
void func() {
static int x = 0;
x++;
printf("static x = %d", x);
}
//...
};

//...
A obj1;
B obj1;

obj1.func(); // should print 1
obj2.func(); // does this print 1 or 2 ??

best regards,
Martin
 
R

Rolf Magnus

Martin said:
Hello.

Is a static Variable in a member function of a class static with regard
to one object, or is it static for all objects of the class?

What does that mean?
Anyway, a static variable in a member function is just the same as a static
variable in any other function. It is initialized when the function is
first called, then re-used in subsequent calls.
That is:
Code:
class A {
// ...
void func() {
static int x = 0;
x++;
printf("static x = %d", x);
}
//...
};

//...
A obj1;
B obj1;

obj1.func(); // should print 1
obj2.func(); // does this print 1 or 2 ??

2
 
M

Martin T.

Rolf said:
Martin said:
That is:
Code:
class A {
// ...
void func() {
static int x = 0;
x++;
printf("static x = %d", x);
}
//...
};

//...
A obj1;
B obj1;

obj1.func(); // should print 1
obj2.func(); // does this print 1 or 2 ??

2

Thanks
 

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

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top