Using static variables in a class with virtual methods.

Is there a problem with accessing static class members in a class with virtual methods?  I am just trying to maintain a reference count to know when to deallocate data.  I keep on getting the following error when I try to compile using VC++:

error LNK2001: unresolved external symbol "private: static int  CWindow::count" (?count@CWindow@@0HA)

Here is the code for the CWindow class:

class CWindow {
public:
  CWindow();  
  virtual void show();
  static void AddRef() { count++; }
private:
  static int count;
};

CWindow::CWindow() {
  AddRef();
}

void CWindow::show()
{
  printf("CWindow::show()\n");
}

prokewlAsked:
Who is Participating?
 
gvgConnect With a Mentor Commented:
You must put an "implimentation" of the variable outside the class just like you put an implementation of a function.  You can also initilize it there.

class CWindow {
public:
  CWindow();    
  virtual void show();
  static void AddRef() { count++; }
private:
  static int count;
};

int CWindow::count = 0;

CWindow::CWindow() {
  AddRef();
}

void CWindow::show()
{
  printf("CWindow::show()\n");
}

I think you can put this just after you define the class but you might have to put it into the CPP file.


0
All Courses

From novice to tech pro — start learning today.