Announcement

Collapse
No announcement yet.

Copy an object

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Copy an object

    I am having a problem with copying an object and keeping them independent after the copy. In the following code I am trying to set up Obj1 and then copy it to Obj2. The problem comes in when I make changes to Obj1 after the copy. It effects Obj2. I read Bob's 'Life and Times of an Object' and it showed copying an object, but I am sure I misread something.
    Frank
    Code:
    #COMPILER PBWIN
    #COMPILE EXE
    #DIM ALL
    
    FUNCTION PBMAIN () AS LONG
      DIM Obj1 AS MyInterface: Obj1 = CLASS "MyClass"
      DIM Obj2 AS MyInterface: Obj2 = CLASS "MyClass"
    
      Obj1.Str1 = "Testing"       'init first object
      ? "1: " + Obj1.Str1         'verify it
      ? "2: " + Obj2.Str1         'still empty
    
      Obj2 = Obj1                 'copy it
    
      ? "2: " + Obj2.Str1         'verify the copy
    
      Obj1.Str1 = "New Test"      'change the original
      ? "1: " + Obj1.Str1         'verify it
      ? "2: " + Obj2.Str1         'WHY DID THIS CHANGE?
    END FUNCTION
    
    CLASS MyClass
      INSTANCE Str1 AS STRING
    
      INTERFACE MyInterface
        INHERIT IUNKNOWN
        METHOD BumpIt(Inc AS LONG) AS LONG
          METHOD = Inc +1
        END METHOD
    
        PROPERTY GET Str1 AS STRING: PROPERTY = Str1: END PROPERTY
        PROPERTY SET Str1(BYVAL Value AS STRING): Str1 = Value: END PROPERTY
      END INTERFACE
    END CLASS

  • #2
    Obj2 = Obj1 does not copy the contents of Obj1 to Obj2. After doing it you don't have two different objects, but an object with two references (if you print OBJPTR(Obj1) and OBJPTR(Obj2) after Obj2 = Obj1 you will see that the two have the same value. To copy the string, do Obj2.Str1 = Obj1.Str1.
    Forum: http://www.jose.it-berater.org/smfforum/index.php

    Comment


    • #3
      Hi Jose'
      Yes, if it was just one property I would do that, but there is more. And as the program evolves (properties added/deleted) you have to remember to update the copy operations. Back to the drawing board...

      Comment


      • #4
        You can add a "copy" method with objx AS MyInterface as the parameter and inside it copy all the instance variables from one object to the other, e.g.

        METHOD Copy (BYREF objx AS MyInterface)
        objx.str1 = str1
        ...
        END METHOD

        And call it as Obj1.Copy(Obj2)
        Forum: http://www.jose.it-berater.org/smfforum/index.php

        Comment


        • #5
          After I didn't find a way to find the size of a object to do a memory copy, I was just starting to play with a copy method as you posted this.
          Thank you, Jose'

          Comment

          Working...
          X