[chuck-users] Passing classes to functions

Hans Aberg haberg at math.su.se
Sun Oct 4 02:57:12 EDT 2009


On 4 Oct 2009, at 02:21, Adam Tindale wrote:

> This is a more direct version of what I meant to say. The problem I
> encountered was that I was hoping to do some operations in a function
> and was hoping that I was passing a copy of an object, much like what
> happens with primitives. Since objects pass by reference then weird
> side effects and bugs can easily creep into a fellow ChucKist's code.

Yes, that is one side effect of it: side effects. The reference  
objects reference the same object on the heap, also when passed into a  
function.

> Anyways, I hope this example is more clear.
>
> --art
>
> class test{
>    0 => int val;
> }
>
> test obj1;
> <<< obj1.val , "original object">>>;
>
> fun void testclasspassing(test i)
> {
>    4 => i.val;
>    <<< i.val, "in function" >>>;
>    // side effect!
> }
>
> testclasspassing(obj1);
> <<< obj1.val , "original object">>>;

So one way to think about it, is that this is the same as C/C++
   void fun void testclasspassing(test* i) {
     4 => i->val;
     <<< i->val, "in function" >>>;
     // side effect!
   }
which in C++ can also be written as
   fun void testclasspassing(test& i)
   {
     4 => i.val;
     <<< i.val, "in function" >>>;
     // side effect!
   }
only that in chuck, the extra reference symbols are hidden away by the  
implementation of the reference object.

So when mutating the object within the function, as it is a reference  
to an object on the heap, it will be mutated there too.

By contrast, when one has a copy over type, a copy will be made, which  
will placed in the function stack. So when changing that within the  
function, that is a copy, and not the original object.

   Hans




More information about the chuck-users mailing list