Archived

This topic is now archived and is closed to further replies.

miko

c++: need a class which knows how many instances of itself was created

Recommended Posts

i need to do do something like this:
class A {
  private:
    static int instance_counter = 0; /* THIS IS A PROBLEM */

  public:
    A { instance_counter++; }
    ~A { instance_counter--; }
    int get(void) { return instance_counter; }
} 
but gcc is complaing i can''t initializate non-const static member variabile. how whould you implement it (ok as far i know static variablies are initalized to 0 automatically but assume they are not because this is a little more complex class than i shown)

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
in the class:
static int instance_counter;

in some source file somewhere:
int A::instance_counter = 0;

Share this post


Link to post
Share on other sites

  
// in A.h file

class A
{
private:
static int instance_counter;
public:
A { instance_counter++; }
~A { instance_counter--; }
int get(void) { return instance_counter; }
};

// in A.cpp file

#include "A.h"

static int A::intstance_counter = 0;


noitice is it EXACTLY the same as the rules for initializing a global variable ... because a static member is basically a global variable qualified by a namespace.

Share this post


Link to post
Share on other sites