Note that there are some explanatory texts on larger screens.

plurals
  1. POfunction modifies a class not referenced
    primarykey
    data
    text
    <p>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</p> <pre><code>#include &lt;iostream&gt; #include &lt;new&gt; #include &lt;time.h&gt; #include &lt;stdlib.h&gt; using namespace std; class list{ public: struct element { int data; element* next; }; element * head; list(){ head=NULL; } ~list(){ while (head!=NULL){ element *e = head-&gt;next; delete head; head = e; } cout&lt;&lt;"Destructing..\n"; } void add (int value){ element *e = new element; e-&gt;data = value; e-&gt;next = head; head= e; } }; void fill10 (class list &amp; l){ for (int i= 0; i&lt;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&lt;&lt;l.head-&gt;data&lt;&lt;endl; cout&lt;&lt;l.head&lt;&lt;endl; cout&lt;&lt;endl&lt;&lt;null(l)&lt;&lt;endl;//when I comment this everything works out as expected cout&lt;&lt;l.head-&gt;data&lt;&lt;endl; //this data is not the same anymore after null is called cout&lt;&lt;l.head&lt;&lt;endl; return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload