0

I am trying to find a solution to a linker error for a static member of a class

Here is the code:

//node.h
class Node{

public:

static vector<Node*> nodePointers; //i will use these pointers to access multiple objects of the same class
int id;
int a;
int b;

friend int add(Node*,int);

void itsMyLife(int);
Node();
};

//node.cpp
void Node::itsMyLife(int x){

int answer=0;
if(nodePointers[x]->a<100){
    answer=add(this,nodePointers[x]->id);
}

cout<<"Answer in node "<<id<<" is "<<answer<<endl;

}

int add(Node* x, int y){

return x->a+x->nodePointers[y]->b;
}

//main.cpp
int* myInts=new int[10];
vector<int*> intVectors;
for(int i=0;i<10;i++)
    intVectors[i]=&myInts[i];

Node* myNodes=new Node[2];

for(int i=0;i<2;i++)
    myNodes[0].nodePointers[i]=&myNodes[i];

myNodes[0].id=0;
myNodes[0].a=10;

When I compile and link it gives me the error:

Undefined reference to Node::nodePointers

Why is that I get this error? I will be grateful for your help. Thanks again.

user2105632
  • 751
  • 1
  • 7
  • 12
  • http://stackoverflow.com/a/12574407/673730 - the "static data members must be defined outside the class in a single translation unit" part – Luchian Grigore May 24 '13 at 21:32

1 Answers1

0

Static class members should be initialized (1)once (2)outside of the class definition. Usually the best place for this is relevant .cpp file.

In other words you should add something like this to your node.cpp:

vector<Node*> Node::nodePointers;
Eugene Loy
  • 12,224
  • 8
  • 53
  • 79