I am reading a book about Binary Search Tree and something weird came up. I came across the following declaration in a function parameter.
BinaryNode * & t
What does it mean? Pointer of the address of t
?
For context, this is the code where I saw this. The private insert
function is a helper function for public insert
function, and private insert
function looks for the right place to insert using recursion.
class BST
{
public:
void insert(const Comparable & item)
private:
BinaryNode *root;
struct BinaryNode
{
Comparable element;
BinaryNode *left;
BinaryNode *right;
BinaryNode(const Comparable & theElement, BinaryNode *lt, BinaryNode *rt) :
element(theElement), left(lt), right(rt) {}
}
void insert(const Comparable & item, BinaryNode * & t) const;
};
Put simply. & means the address-of, you will see that in placeholders for functions to modify the parameter variable as in C, parameter variables are passed by value, using the ampersand means to pass by reference. * means the dereference of a pointer variable, meaning to get the value of that pointer variable.
The fundamental rules of pointer operators are: The * operator turns a value of type pointer to T into a variable of type T . The & operator turns a variable of type T into a value of type pointer to T .
The ampersand symbol & is used in C++ as a reference declarator in addition to being the address operator. The meanings are related but not identical. int target; int &rTarg = target; // rTarg is a reference to an integer.
The ampersand is the address of operator. It returns the memory location of a variable and that's the only way it's used, prefixed to a variable like the engine on a train. The variable doesn't even have to be initialized, just declared.
In your expression BinaryNode * & t)
BinaryNode* & t
------------- -----
BinaryNode pointer t is reference variable
so t
is reference to pointer of BinaryNode class.
Pointer of the address of t?
You are confused ampersand &
operator in c++. that give address of an variable. but syntax is different.
ampersand &
in front of some of variable like below:
BinaryNode b;
BinaryNode* ptr = &b;
But following way is for reference variable (its simple not pointer):
BinaryNode b;
BinaryNode & t = b;
and your is like below:
BinaryNode b;
BinaryNode* ptr = &b;
BinaryNode* &t = ptr;
It's a reference to pointer. You can change pointer in this function and it will be changed outside.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With