2

I did it in pure C but now I am trying to implement a binary search tree in C++. Most of the code is the exact same but instead of malloc() I want to use the new operator. However, I am getting this error:

Undefined symbols for architecture x86_64:
  "operator new(unsigned long)", referenced from:
      GetNewNode(int) in BstTreeV3-beb469.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

This is my code on ideone. Click here to view it.

Node* GetNewNode(int data) {
    Node *newNode = new Node();
    newNode->data = data;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

void Insert(Node **root, int data) 
{
    if (*root == NULL) { // empty tree
        *root = GetNewNode(data);
    }
    else if ((*root)->data < data) {
        Insert(&((*root)->left), data);
    }
    else {
        Insert(&((*root)->right), data);
    }
}

I understand this may not be the best implementation method, but I am just practicing. If you have any recommendations on how to implement a BST then please feel free to comment.

jww
  • 97,681
  • 90
  • 411
  • 885
nodebase
  • 2,510
  • 6
  • 31
  • 46
  • 3
    What's your compile line? – Tony Delroy Nov 17 '14 at 07:54
  • 2
    If you're using `new` (and `delete`, I hope) then you're not programming C, so I removed that tag. And that's probably the reason your linking fails, because you build with `clang` which doesn't link with the C++ runtime library, you should build with `clang++` instead, which automatically links with the C++ runtime library (or manually link with the C++ runtime library). – Some programmer dude Nov 17 '14 at 07:56
  • Ahh yes, Sublime was still using the C build system I made instead of auto using C++ based on the source file type. I wonder why its not switching build systems automatically. Should I delete my original question? – nodebase Nov 17 '14 at 07:59
  • Some compilers decide whether to compile as C or C++ depending on extension .c or .cpp. Some do not. But compiler errors aside, there are also fundamental design problems in your code, you need to convert it to an OO design, as shown in my answer. – Lundin Nov 17 '14 at 08:01

1 Answers1

1

For the program to make any sense, it should be like this:

class Node
{
   private:
     int   data;
     Node* left;
     Node* right;

   public:

     Node()
       :data(0), left(NULL), right(NULL)
     {}

     Node(int d)
       :data(d), left(NULL), right(NULL)
     {}
};


...

*root = new Node(data);

If you don't use these language features, you might as well stick to C.

Although it seems very likely that the specific error you got came from compiling C++ code with a C compiler, as pointed out in the comments to your question.

Lundin
  • 195,001
  • 40
  • 254
  • 396