I am experimenting with a linked list. My function "null" seems to modify my list even though the list is not passed by reference. I've read that these problems can occur with objects that are passed as normal call-by-value parameter and that it is one the reasons that data inside a class is not declared as an public member in good OOP. I have tried the null function as an member function of the list and it works fine, but I still would like to understand why this way doesn't work properly. Thanks
#include <iostream>
#include <new>
#include <time.h>
#include <stdlib.h>
using namespace std;
class list{
public:
struct element {
int data;
element* next;
};
element * head;
list(){
head=NULL;
}
~list(){
while (head!=NULL){
element *e = head->next;
delete head;
head = e;
}
cout<<"Destructing..\n";
}
void add (int value){
element *e = new element;
e->data = value;
e->next = head;
head= e;
}
};
void fill10 (class list & l){
for (int i= 0; i<10 ;i++){
l.add((rand()%10)+1);
}
}
bool null (class list l){
if (l.head!=NULL){ return false;}
return true;
}
int main ()
{
srand(time(NULL));
class list l;
fill10(l);
cout<<l.head->data<<endl;
cout<<l.head<<endl;
cout<<endl<<null(l)<<endl;//when I comment this everything works out as expected
cout<<l.head->data<<endl; //this data is not the same anymore after null is called
cout<<l.head<<endl;
return 0;
}