Static variables inside member functions

A

Azdo

Hello,

if I code something like this,

class A{
void f(){
static i=0;
}};

int main(){
A a1,a2;

return 0;
}

will a1::f::i and a2::f::i be identical?

TIA!
 
A

Azdo

Suman ha escrito:
//calling f() later is a pain otherwise
public:

Sorry, I forgot about that.
Run the code, and you will know!

Yes, but if I run the code, I could not say from the results if it is
the expected behaviour or the compiler is wrong.

Thank you anyway
 
J

Jaspreet

Azdo said:
Hello,

if I code something like this,

class A{
void f(){
static i=0;
}};

int main(){
A a1,a2;

return 0;
}

will a1::f::i and a2::f::i be identical?

TIA!

Assuming you have your public and private scope written correctly.

Yes the static data members are sharable among different instances of
the class. Soo, if a1 modifies i that changed value woudl be reflected
when i is accessed using a2.
 
A

Azdo

Jaspreet ha escrito:
Assuming you have your public and private scope written correctly.

Yes, my fault.
Yes the static data members are sharable among different instances of
the class. Soo, if a1 modifies i that changed value woudl be reflected
when i is accessed using a2.

The difference here is that 'i' is not a static member of the class but
a static variable of a function (which happens to be a function
member). I don't know if we can consider 'i' a member of the class, can
we?

Thank you.
 
J

Jaspreet

Azdo said:
Jaspreet ha escrito:

Yes, my fault.


The difference here is that 'i' is not a static member of the class but
a static variable of a function (which happens to be a function
member). I don't know if we can consider 'i' a member of the class, can
we?

Oops. I apologise for that. Did not really notice that. Yes i is a
static variable for a function and cannot be termed as a static
variable of the class. Coming to your original question , yes i will be
same if you access it from a1 or a2. As long as you are in the program
i will continue to be available.

BTW, ** static i=0; ** is deprecated since you need to explicitly give
the data-type.
 
H

Howard

Azdo said:
Hello,

if I code something like this,

class A{
void f(){
static i=0;
}};

int main(){
A a1,a2;

return 0;
}

will a1::f::i and a2::f::i be identical?

Yes, they will be the same, because f is the same. Member functions are
shared among instances of the class. There is not one f for each instance
of A. So, any static variables in f will be identical for all instances of
A (within a given process).

-Howard
 

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
473,769
Messages
2,569,581
Members
45,056
Latest member
GlycogenSupporthealth

Latest Threads

Top