Easy way to copy class instance?

Phil7

Active Member
3rd Party Tool Dev
Joined
Jun 26, 2017
Is there an easy way to copy an instance? Make a clone object?
Until now I just copied all the Fields to a new object of that class, but this time my class has some collections/arrays in it, I wanted to know if there is an other way.

BTW: Am I correct with this: "=" assigns only values (copies) for int, float, string types and it assigns something pointer like to arrays, objects (incl. maps, stacks, lists)?
 

magic

Active Member
3rd Party Module Dev
3rd Party Tool Dev
Joined
Mar 5, 2018
Am I correct with this: "=" assigns only values (copies) for int, float, string types and it assigns something pointer like to arrays, objects (incl. maps, stacks, lists)?
I think.... Yes, other than basic type, Cerberus use reference to a memory address where the object is really stored. When no more variable refer to it the GC will free that memory. String also object but I thing every assignment for a string, a compiler create a duplicate of it.
 

Gerry Quinn

Active Member
Joined
Jun 24, 2017
There is no easy way to automatically copy an object, because you might want to do it in different ways. For example, you might be happy to just copy pointers to the same object fields (this is known as a shallow copy) or you might want to create entirely new instances of the object fields (a deep copy).

If you copied a sprite, it might have an image field where you would want a shallow copy, and a position field where you would want a deep copy - so you would have an object and its identical twin which start in the same place but can move separately.

Of course if your field objects have their own cloning methods already, or you have functions to copy arrays etc., it gets easier. If the position has a copy constructor, your sprite code might look like:

Cerberus X:
Class Sprite
    
    Field img:Image
    
    Field pos:Position

    Method New( other:Sprite )
        img = other.img
        pos = New Position( other.pos )
    End
    
End


Class Position

    Field x:Int
    Field y:Int
    
    Method New( other:Position )
        x = other.x
        y = other.y
    End

End
 

Phil7

Active Member
3rd Party Tool Dev
Joined
Jun 26, 2017
Thanks! In my case it would be quite handy to have a way to do a complete deep copy. But if there was one I would have definitely not been aware of the consequences like having all the recource data like images twice.
So deep copy should be avoided if possible, because it can lead to a lot of operations that might not be necessary.

One idea that came to my mind, dealing with this, was that it would be really nice to enhance the array functionality (which can easily be transfered to lists, maps, etc.:
1. Copy() Method for a simple deep copy
2. InsertArray(InsArray[], Position:Int=-1) Method to insert or append an Array to an exisisting one.
 
Top Bottom