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.

1

1 Answer 1

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;
4
  • Is there a point to the ` = vector<Node*>()` part? May 24, 2013 at 21:45
  • Thanks leo, it removed the undefined reference error. Any idea why the above code might cause a "segmentation fault"? May 24, 2013 at 21:49
  • @LuchianGrigore good point. Java habbit. Fixed.
    – Eugene Loy
    May 24, 2013 at 22:16
  • @user2105632 probably you have a crash due to that you haven't allocated enough space for elements in intVectors. See docs on how to o this here: cplusplus.com/reference/vector/vector/vector
    – Eugene Loy
    May 24, 2013 at 22:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.