Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Static variables

Status
Not open for further replies.

VincentP

Programmer
Apr 1, 2001
116
Hi,

I have multiple instances of a class which has a function with static variables.

Example:

class CMyClass{
int myMethod();
...
};

int CMyClass::myMethod()
{
static int i = 0;
...
return i++;
};

My problem: I would like to have the different instances of MyClass to not interfere with each other.

Say I have:

...
int j;
CMyClass o1, o2;
j = o1.myMethod(); // j is set to 0
j = o1.myMethod(); // j is set to 1
j = o2.myMethod(); // j is set to 2, but I would like 0, because I am now dealing with o2, not o1!
...

The only way I figured out how to go around this, is to add a member variable to CMyClass and use it instead of a local static variable, but I sure hope there is a better way! Any suggestion?

The example is really simplified, but really a local static variable is best in my case.

Thanks,

Vincent
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top