For this simple singly linked list, I thought pass by reference stores address, not the copy of object so it's more efficient, then why do I have to 'dereference' head in main if I want to use insert_at_end function which passes by reference (rather than pass by ptr to ptr). I think I sort of understand, b/c references are the actual objects, then is pass by reference passing address too, but differently than pass by ptr to ptr (pass by address)...
Just to clear it up.
Code:
#include <iostream>
using namespace std;
class sll//I should use struct for backwards compatability w/ C (in case I need to work w/ C legacy code or low level programming like bitfields
// in a struct to talk to registers/other hardware directly)
{
public:
int data;
sll* next;
};
//NB: if you pass an object (class/struct) by reference, the instantiated obj must be passed, NOT a ptr to the obj??
void insert_at_end(sll& head, int d)
{
sll newNode;
newNode.data = d;
newNode.next = NULL;
if ( !head )//if empty list
{
head = &newNode;
return;
}
//else not empty list
for ( sll cur = head; cur != NULL; cur = cur.next )
if ( cur.next == NULL )//if you found tail node, new node linked after it
{
cur.next = newNode;
return;
}
}
int main()
{
sll* head = NULL;
sll node; node.data = 9000; node.next = NULL;
head = &node;
insert_at_end(*head, 90);
return 0;
}
EDIT: actually I just wrote this code out and found out I can't mix reference to objects and w/ straight ptrs to obj (the head var I created in main I mean). But is pass by reference still similar to pass by address where the memory location of the object is passed but references are more controlled syntax...I'll look into it (I found this excellent tutorial for anyone in the future: http://www-cs-students.stanford.edu/...nfo/references)