0

(old questions answered, i need to compile two cpp files together. New questions on infinite priting of "default constructor" is posted.)

I have three files.

node.h defines node class with constructor, destructor declaration but i want to put the actual definition into node.cpp

class node{
private:
  int i;
  node *next;
public:
  node();
  node(int);
  ~node();
  void setNode(int);
};

node.cpp contains the definition of constructor/destructor in the following format. It also "#include "node.h""

node::node()
{
  node::setNode(0);
  cout<<"default constructor"<<endl;
  node *next = new node;
}
node::node(int value)
{
  node::setNode(value);
  cout<<"value constructor"<<endl;
  node *next = new node;
}
node::~node(){
  cout<<"default destructor"<<endl;
  delete next;
}
node::setNode(int value){
  i = value;
} 

in the nodelist.cpp, it is my main func for now. it includes "node.h". But the compilation seems can't find the constructor and destructor

g++ nodelist.cpp
/tmp/cc6PoQNR.o: In function `main':
nodelist.cpp:(.text+0x11): undefined reference to `node::node()'
nodelist.cpp:(.text+0x22): undefined reference to `node::~node()'
collect2: error: ld returned 1 exit status

Can anyone explain what is the issue?

If possible, maybe elaborate more on some knowledge behind this issue that i lack of.

Thanks guys. I need to compile node.cpp and nodelist.cpp together.

The next question is:

in my nodelist.cpp, i just typed

int main(){
node x;
return 0;
}

but it is printing infinite number of "default constructor".

WriteBackCMO
  • 629
  • 2
  • 9
  • 18
  • 3
    `g++ node.cpp nodelist.cpp` – Chol Nhial Aug 28 '17 at 06:45
  • Elaborate: If you want to use code, you need to compile it and link the results to your program. – WhozCraig Aug 28 '17 at 06:45
  • thanks. I copycat the code from a video in udemy. But he used the IDE, so it is like click the button of building and running, but i ran in linux, so thought would only need to compile the nodelist.cpp. – WriteBackCMO Aug 28 '17 at 06:49
  • 1
    Possible duplicate of [What is an undefined reference/unresolved external symbol error and how do I fix it?](https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix) – user0042 Aug 28 '17 at 06:50

1 Answers1

1

node *next = new node; this line inside default constructor will call another default constructor for node to be set into next, which will call another default constructor, which will... etc

set next to nullptr - you do not want to allocate more than one node at a time

Artemy Vysotsky
  • 2,694
  • 11
  • 20