Value of static variable after object re-created.

R

rhd

Hi,

- C++ class with a private member function.
- Private member function declares a static int locally with an
initial value of 0 .
- A single instance of the class is created.
- The object calls the member function a number of times, each time
the local variable is incremented.

- Eventually the object calling the member function is deleted.
Static int has a non-zero value at time of deletion.

- A new instance of the class is created.

What will be the value of the static int within the member function
when the object is re-created?
- Will it be 0 or the last value it held before the deletion of the
initial object?

If there were multiple instances of the object would this static
variable, within a non-static member function, be shared between all
instances or would all instances receive their own "static" copy?

Note - Using Microsoft Visual Studio C++ for Windows CE.

rhd
 
C

Colander

Hi,

- C++ class with a private member function.
- Private member function declares a static int locally with an
initial value of 0 .
- A single instance of the class is created.
- The object calls the member function a number of times, each time
the local variable is incremented.

- Eventually the object calling the member function is deleted.
Static int has a non-zero value at time of deletion.

- A new instance of the class is created.

What will be the value of the static int within the member function
when the object is re-created?
- Will it be 0 or the last value it held before the deletion of the
initial object?

If there were multiple instances of the object would this static
variable, within a non-static member function, be shared between all
instances or would all instances receive their own "static" copy?

You can use static vars even without an instance!

class A
{
public:
static int i;
};

int A::i;

int main()
{
A::i = 2;
}

When your program runs there will be already exact one instance of the
static var, in mine code the int A::i;. Just before main these are
instantiated (in apparent random order).
 

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
474,291
Messages
2,571,453
Members
48,137
Latest member
IndiraMcCo

Latest Threads

Top