C++ question: class-scoped variable shared between all instances of the class?

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!

MAGIC static

They have to have a definition.

1 Like

In your header file...

class myThing {
  private:
    int instanceNumber;
    static int instanceCounter;
  public:
    myThing() { instanceNumber = instanceCounter++; }
};

In exactly one place in a CPP file...

int myThing::instanceCounter;

I just declare something in the .cpp file. Is that not sufficient?

-jim lee

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.

There are a few differences...

  • 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.

maybe a class that manages one or more dynamically allocated objects of another type of class

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.