Is there a C++ concept that allows a variable to be shared between all instances of a given class, but whose name has scope only within the methods of those class?
For example, suppose I want to keep track of how many instances of an object have been created:
class myThing {
private:
int instanceNumber;
MAGIC int instanceCounter;
public:
myThing() { instanceNumber = instanceCounter++; }
}
What I'm looking for would replace "MAGIC", and cause all create myThings to see the fully-incremented value of instanceCounter
I don't think so since all instances are effectively self-contained and thus unaware of each other.
Isn't it a feasible solution to have some kind of wrapper that is aware of all the class instantiations instead of trying to solve this from within the class?
Edit: disregard the above; @Coding_Badly has the solution below!
it's somewhat conventional to maintain a list of "allocated" data structures, possibly along with counts. rather than "free" an allocated data, it would be put on a separate list and reused rather than allocating new. it may make sense to allocated more than one data whenever one is needed; the additional data structure immediately put on the available list.
instanceCounter is scoped. Being private it can only be touched by a myThing method. Limiting scope is a cheap way to reduce bugs.
instanceCounter is accessible to all myThing methods no matter which module contains their definition. While it is common to place all methods of one class in one module that is not a requirement. @westfw may prefer the myThing code to be split across modules. Making instanceCounter class data means @westfw does not need to do anything beyond what's posted above.