0

I am creating a binary tree program and I would like to overload a few operators. I have tried overloading the + operator so that when I write something like myTree + 5, it would add 5 as a node on the tree.

This is my code:

BST myTree;

void operator+(BST left, int right) {
    myTree.addLeaf(right);  
}

int main() {    
    vector<int> treeKeyList;
    srand((unsigned)time(NULL));
    int before = rand() % 20 + 1;  
    for (int i = 0; i < before; i++) {
        int after = rand() % 20 + 1;
        treeKeyList.push_back(after);
        cout << treeKeyList[i] << " ";
    }
    cout << endl;

    for (int i = 0; i < treeKeyList.size(); i++) {
        myTree + treeKeyList[i];
    }
}

At the moment, it seems to run fine through one loop, however it crashes when it tries to add the second value with a segmentation fault error. I think the issue must be in the code I have shown, as before I added the overloading it worked fine. If I did this instead:

for (int i = 0; i < treeKeyList.size(); i++) {
    myTree.addLeaf(treeKeyList[i]);
}

It works absolutely fine. Any ideas?

user3746428
  • 11,047
  • 20
  • 81
  • 137
  • 2
    1) Your overloading is not inuitive becuase operator "+" does not normally mutates it's left hand-side. 2) Even if you think it modifies left hand-side - it actually copies it while passing to function and mutates the copy, so it probably doesn't act like you planned it to, – Predelnik Mar 25 '15 at 22:52
  • 1
    [This](http://stackoverflow.com/q/4421706/3425536) might help. – Emil Laine Mar 25 '15 at 22:53
  • Your operator+ takes its left argument by value, mutates it, and then throws it away. Did you intend to add a node to a temporary copy of your tree, which you can never access? – Useless Mar 25 '15 at 22:55
  • Could you post your BST implementation? As the other comments say you've got an "interesting" operator overload, but that in itself shouldn't cause segmentation faults. I wonder if there's something occuring as a result of deleting the left param of your operator – MrShiny608 Mar 25 '15 at 22:58
  • Looks like you want to overload `+=` instead. – Emil Laine Mar 25 '15 at 22:58
  • @zenith Ideally, what I would like to do is to be able to do `tree = tree + 5`. – user3746428 Mar 25 '15 at 23:04

1 Answers1

1

Most likely you need to take the BST as a reference. Also consider using += instead of +.

rlbond
  • 65,341
  • 56
  • 178
  • 228
  • That fixed the problem. Thanks! I realised afterwards that I meant to do `tree = tree + 5`, rather than `tree + 5`, but hopefully it won't be too difficult to change. – user3746428 Mar 25 '15 at 23:34