views:

89

answers:

2

I'm getting an undefined reference to one private methods in a class. Here is a short snippet of the code (but the whole thing currently is in one source file and not separated into header and source files).

#include <iostream>

using namespace std;

struct node
{
    int key_value;
    node *left;
    node *right;
};

class btree
{
    node *root;
    btree();
    ~btree();
    void destroy_tree(node *leaf);

    public:
    void destroy_tree();
};

btree::btree()
{
    root = NULL;
}

btree::~btree()
{
    destroy_tree();
}

void btree::destroy_tree()
{
    destroy_tree(root);
}

void destroy_tree(node *leaf)
{
  if(leaf!=NULL)
  {
    destroy_tree(leaf->left);
    destroy_tree(leaf->right);
    delete leaf;
  }
}

int main()
{
    return 0;
}

The compiler outputs "undefined reference to `btree::destroy_tree(node*)' for this line:

destroy_tree(root);

but isn't the definition of that function immediately right below it?

+4  A: 

Your destroy_tree overload is not scoped to btree. The implementation is missing btree:: and is required since it is not inside the class definition:

 void btree::destroy_tree(node * leaf)
 {
   if(leaf!=NULL)
   {
     destroy_tree(leaf->left);
     destroy_tree(leaf->right);
     delete leaf;
   }
}
sean e
+1  A: 

The main problem I can see is that:

void destroy_tree(node *leaf)

should be:

void btree::destroy_tree(node *leaf)

Also there is no way to create a btree object. You should maybe do this:

class btree
{
public:
    btree();
    ~btree();

    void destroy_tree();

private:
    void destroy_tree(node *leaf);
    node *root;
};
Shane Powell