0

I am writing binary search tree program in c++. I have a node class as follows:

template<typename T> class BinaryTreeNode{ private: T _data; BinaryTreeNode<T>* _left; BinaryTreeNode<T>* _right; public: T& data() { return _data; } const T& data() const { return _data; } BinaryTreeNode<T>* left() { return _left; } const BinaryTreeNode<T>* left() const { return _left; } BinaryTreeNode<T>* right() { return _right; } const BinaryTreeNode<T>* right() const { return _right; } }; 

In my binary search tree class I have a method to add a node as follows

 template<typename T> void BinarySearchTree<T>::_push(BinaryTreeNode<T>** root ,BinaryTreeNode<T>* node){ if(*root == NULL){ *root = node; }else{ if(node->data() < (*root)->data()){ _push(&((*root)->left()), node); }else{ _push(&((*root)->right()), node); } } } 

I am getting following error in _push():

binary_tree.h:32:9: error: lvalue required as unary ‘&’ operand _push(&((*root)->left()), node); ^ binary_tree.h:36:9: error: lvalue required as unary ‘&’ operand _push(&((*root)->right()), node); ^ 

Is something wrong with this the syntax? Can anybody kindly explain what is wrong here?

4
  • What about using a reference: template<typename T> void BinarySearchTree<T>::_push(BinaryTreeNode<T>*& root ,BinaryTreeNode<T>* node) Commented Nov 1, 2014 at 13:45
  • 1
    The function left and right return pointers by value. You can't take address of a temporary. Haven't looked at the logic of your code, I think you simply want to the pointers that those functions return - so just get rid of &. Commented Nov 1, 2014 at 13:45
  • BTW, this has nothing to do with templates. In general, it's often easier to debug if you write a non-template prototype first. Commented Nov 1, 2014 at 13:50
  • I missed the fact that I was returning pointer by value, so a temporary will be created for that. I should have written non template version first Commented Nov 1, 2014 at 14:11

1 Answer 1

4
_push(&((*root)->left()), node) 

You are trying to take the address of temporary returned from left function.

One good advice always test your class for design issues before converting it into template class. That way templates would save some insidious blames.

Sign up to request clarification or add additional context in comments.

1 Comment

I missed to notice the fact that I returning pointer by value. I am changing left to return by reference. I should have tried non template version first, my apologies.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.