Copacel
Copacel

Reputation: 1390

Overloading operator + for inserting a node in a BinaryTree

Those are my classes for the Binary Tree :

class Node
{
    friend class BinaryTree;
    int value;
    Node *left, *right;
};

class BinaryTree
{
private :
    Node *first ;
public :
    void insert_node(int x);
    void delete_node(int x);
    void in_order_traversal();
    void print_leafs (Node *first);
    void print_leafs2 ();
    int get_height();
    BinaryTree();
    ~BinaryTree();

    // operator oveloading
};

I want to overload the + operator so I can insert one new element to the tree, the sequence should be like this :

int x;
BinaryTree *bt;
x + bt; // or bt + x;

I already have a method that insert a node to the tree, and all I have to do is to call that method in the overloading operator + code. This is how I tried to do it :

//inline declaration
friend BinaryTree& operator + ( BinaryTree& bt, const int x)
{
    bt.insert_node(x);
    return bt;
}

I don't know why but when I debug this code, the line

bt + x;

is ignored by the compiler.

Any help will be appreciated :)

Upvotes: 0

Views: 94

Answers (1)

R Sahu
R Sahu

Reputation: 206607

Since x is declared as an int and bt is declared as a pointer, using x + bt; or bt + x; evaluates to a pointer and the value is discarded.

In order to invoke the function friend BinaryTree& operator + ( BinaryTree& bt, const int x), the LHS of the operator must be an object of type BinaryTree, not a pointer to a BinaryTree.

You need to use:

*bt + x;

That's just the syntactic part. Semantically speaking, that operator overload function does not seem right.

When you use

int a  = 10;
a + 20;

the value of a is not changed. The last line simply evaluates to 30 and the value is discarded.

If you use

int b = a + 20;

b gets assigned the value of 30 but a remains unchanged. You may want to create similar semantics for your operator overload function.

BinaryTree bt1;             // Create an empty tree.
BinaryTree bt2  = bt1 + 1;  // bt2 contains everything in bt1 + 1.

In that case, change the function to:

friend BinaryTree operator + ( BinaryTree const& bt, int x)
//               |                       |           ^^^ No need for const
//               |                       ^^^^^^^^ Change it to const&
//              ^^^ Change the return type to be an object, not a reference.    
{
   BinaryTree ret(bt);  // Provide a proper copy constructor
   ret.insert_node(x);
   return ret;
}

Upvotes: 2

Related Questions