I’m curious on how to implement such a function. For example,
I have something like:
class Node {
public:
int dataItem;
Node *next;
};
void foo(int number, Node & n) {
// do something
}
Then in main I need to call that function, something like this does not work:
int main () {
Node *n;
int data;
foo(data, n);
return 0;
}
I’m going to need a wrapper function in order to pass the node by reference in main and this is where I’m struggling, I’m just not sure how to approach the problem. I’ve tried some ideas, I’ve read a lot online, but I’m just not grasping it. Any help understanding how to implement this wrapper function would be fantastic.
You don’t have a
Nodeat all. You just have a pointer toNodethat doesn’t point anywhere in particular yet (yourdatais also uninitialized). A reference parameter of typeNode&requires you to pass aNode, not aNode*, so what you really want is:Alternatively, if you really needed
nto be a pointer, you could do the following:However, I don’t advocate the use of raw pointers in this situation – you have to remember to
deleteto avoid memory leaks. You could instead usestd::unique_ptr<Node> n(new Node())instead ofNode* n = new Node(), but using anNodewith automatic storage duration (as in the first example) is much preferred.