PDA

View Full Version : Using a static member in a class



feraudyh
28th April 2010, 09:57
Hello,
This is just about C++ and it's very simple.
I'm using QtCreator and MingW .
I define a new console project with the usual main.cpp and a class called myclass. The header is as follows:

class MyClass
{
public:
MyClass();
static int getInstanceCount(){return _instanceCount;}
private:
static int _instanceCount;
};
The code is as follows

#include "myclass.h"

MyClass::MyClass()
{
_instanceCount++;
}


The code of main is as follows:

#include <QtCore/QCoreApplication>
#include <iostream>
using namespace std;

#include "myclass.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MyClass foo;
cout<<MyClass::getInstanceCount();
return a.exec();
}


The trouble is that this fails at link time with the repeated message that there is an
undefined reference to MyClass::_instanceCount

What have I done wrong and what can I do to fix it?
Thankyou.

psih128
28th April 2010, 10:10
your static member has been declared, but not initialized.

Put this in your .cpp file:

int MyClass::_instanceCount = 0;
Or change the declaration in the .h file:

static int _instanceCount = 0;

BTW, this is not related to Qt in any way

feraudyh
28th April 2010, 10:34
I realise that this is not related to Qt in any way. It was just not obvious to find a thread to ask about it and it was pretty easy to answer.

Thank you.

squidge
28th April 2010, 10:53
So a better forum would be General programming, rather than Qt programming, which clearly states "For general, non-Qt programming issues."

feraudyh
29th April 2010, 10:58
Yes, how embarassing.