What is the return type "BST&" meaning?

Viewed 67

I tried to implement a simple BST with a member of class that insert a value into the tree. I followed the snipping code like below:

class BST {
public:
    int value;
    BST* left;
    BST* right;

    BST(int val);
    BST& insert(int val);
};

But I don't understand what the return type BST& means. What does it mean ?

1 Answers

This is a reference to an instance of BST. It means that you can change the BST through that reference, e.g.:

BST tree(1);
BST &newNode = tree.insert(3);
newNode.value = 4;

The code snippet above will create a tree with value 1, then insert a node with value 3, but replace that value with 4 in the third line.

For more information about C++ references, consider reading:

What are the differences between a pointer variable and a reference variable in C++?

Related