• Advertisement

Archived

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

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

This topic is 5406 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
declare a static int num; that you inc in contructor and dec in destructor.

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

  • Advertisement