0

Guys I have a quick general knowelege question.
When defining a function in any programming langauge that will return a pointer to a linked list created in the function, can we return that pointer by reference?

If so, can you provide me with a SIMPLE example of the following scenarios:
1- when it is necessary to return a pointer by reference.
2- when it is sufficent to return a pointer by value.

Thanks for any information.

2
Contributors
1
Reply
2
Views
4 Years
Discussion Span
Last Post by firstPerson
1

Yes in C++ you can return a pointer by reference, doing so will allow you to change the pointing address of the pointer and have it affect out of scope. For example

void reallocateRef(Node*& node, int newValue){
    node = new Node(newValue);
}
void reallocateNoRef(Node* node, int newValue){
    node = new Node(newValue);
}
//...
Node * n1 = new Node(-1);
Node * n2 = new Node(1);
reallocateRef(n1, 0); //   n1.value = 0 instead of -1
reallocateNoRef(n2,0); // n2.value is still 1 instead of 0

As for what it is good for, it depends on context, somtimes it plays a good role for helper function and other times you just might need it. Usually you just pass pointer by value, but if you need to change what it is pointing to then it is necessary to pass by reference. There could be similar reasoning for returning by value versus ref for pointers.

Edited by firstPerson

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.