I have this class that has a static member. it is also a base class for several other classes in my program. Here's its header file:
#ifndef YARL_OBJECT_HPP
#define YARL_OBJECT_HPP
namespace yarlObject
{
class YarlObject
{
// Member Variables
private:
static int nextID; // keeps track of the next ID number to be used
int ID; // the identifier for a specific object
// Member Functions
public:
YarlObject(): ID(++nextID) {}
virtual ~YarlObject() {}
int getID() const {return ID;}
};
}
#endif
and here's its implementation file.
#include "YarlObject.hpp"
namespace yarlObject
{
int YarlObject::nextID = 0;
}
I'm using g++, and it returns three undefined reference to 'yarlObject::YarlObject::nextID
linker errors. If I change the ++nextID
phrase in the constructor to just nextID
, then I only get one error, and if I change it to 1
, then it links correctly. I imagine it's something simple, but what's going on?
++nextID
to1
.nextID
then you don't need to define it. So that's not an indication for the presence of that definition in the final executable. In fact, the fact that it works is an indicate that you do miss to link against the implementation file.