How do you duplicate an object variable?

In the previous section, you learned to create an object, which assigns an OBJECT REFERENCE to the object variable:

LOCAL object1 AS MyInterface
LET object1 = CLASS "MyClass"

What if you need to duplicate it?  Well, you first must decide whether you want to create a completely new object, or if you just want a second object variable which points the same object. This is a very important distinction.  With two objects, they each have their own set of INSTANCE variables.  The variables in each set remain independent of the other set until they are destroyed.  You would create two objects by writing:

LOCAL object1, object2 AS MyInterface
LET object1 = CLASS "MyClass"
LET object2 = CLASS "MyClass"

If you have two object variables pointing to the same object, they would share the same set of INSTANCE variables.  You would create two OBJECT REFERENCES to one OBJECT by writing:

LOCAL object1, object2 AS MyInterface
LET object1 = CLASS "MyClass"
LET object2 = object1

Of course, now we can take this one step further.  You already know that an OBJECT may have two (or even more) interfaces defined in a CLASS.  How would you actually use two interfaces on the same object?  Just declare an object variable for each interface, much like:

LOCAL object1 AS MyInterface
LOCAL object2 AS HisInterface
LET object1 = CLASS "MYClass"
LET object2 = object1

The code is very much like the preceding example, except that the two object variables are declared as two different interfaces. When the last line is executed, PowerBASIC looks at the object variables to determine if they represent the same interface or not. If they do, it simply creates an extra variable, pointing to the same object.  If they differ, PowerBASIC checks object to ensure the new interface is supported.  If so, it creates a new OBJECT REFERENCE via the new interface, and assigns it to object2.  It's just that simple!

The final issue in this topic is how to destroy an object variable. Generally speaking, you do nothing at all.  When an object variable goes out of scope, PowerBASIC will handle all the messy details for you.  For the most part, just forget about it.  However, in the rare case that you need to destroy an object variable at a specific time and place, you can do so with the following statement:

object1 = NOTHING

Setting an object variable to NOTHING handles it all for you.

 

See Also

What is an object, anyway?

Just what is COM?

How do you create an object?

How do you call a Direct Method?