linked list - Passing a object by reference in c++ -
this noobie question, i'm not sure how pass reference in c++. have following class sets node , few functions.
class node { public: node *next; int data; node(int dat) { next = null; data = dat; } node* getnext() { return next; } void setnext(node *n) { next = n;} void reverse(node *root) { node *previous = null; while(root != null) { node *next = root->getnext(); root->setnext(previous); previous = root; root = next; } root = previous; } };
now, purpose of little class create singularly linked list , have ability reverse it. , seems work fine, if return node named 'previous' @ end of reverse.
but @ main function:
int main() { node *root = new node(1); node *num2 = new node(2); node *num3 = new node(3); node *num4 = new node(4); root->setnext(num2); num2->setnext(num3); num3->setnext(num4); root->printlist(); root->reverse(root); root->printlist(); return 0; }
printlist() omitted sake of space, prints list given node. problem is, when root->reverse(root) called, root doesn't end pointing 'previous'.
the output this:
1 2 3 4 // value of previous reverse function 4 1
i don't understand output. care explain what's happening? (why isn't list reversed though if did root = root->reverse(root) reverse returns previous, would) why root points itself? i'm new c++ , appreciate help!
c++ has support reference semantics. therefore, given function:
void foo(bar& bar);
to pass reference do:
int main() { bar whatsit; foo(whatsit); return 0; }
that's it!
this commonly confused passing pointer, function such as:
void foo(bar* bar);
you do:
int main() { bar whatisit; foo(&whatsit); return 0; }
the difference matter of semantics: - reference valid. there no reason check null pointer. - pointer null, , such, should checked.
it is, however, possible reference refer null pointer, however, if programmer decides evil , abuse reference semantics, principle remains.
Comments
Post a Comment