Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reason for not instantiating an object at the time of declaration?

Tags:

vb6

I had to delve into some VB6 code recently and I saw this pattern all over the place:

dim o as obj
set o = new obj

Why not this?

dim o as new obj

I remember from 15 years ago that there was a good reason for this, but I can't remember what it was now. Anyone remember? Is the reason still valid?

like image 538
AngryHacker Avatar asked Nov 13 '11 20:11

AngryHacker


People also ask

What is the difference between declaration and instantiation an object?

Declaration: The code set in bold are all variable declarations that associate a variable name with an object type. Instantiation: The new keyword is a Java operator that creates the object. Initialization: The new operator is followed by a call to a constructor, which initializes the new object.

What happens when you instantiate an object?

An instance of an object can be declared by giving it a unique name that can be used in a program. This process is known as instantiation. A class can also be instantiated to create an object, a concrete instance of the class.

Why do we instantiate an object?

Instantiation allocates the initial memory for the object and returns a reference. An instance is required by non-static methods as they may operate on the non-static fields created by the constructor.

What does it mean to instantiate an object from a class?

Instantiate (a verb) and instantiation (the noun) in computer science refer to the creation of an object (or an “instance” of a given class) in an object-oriented programming (OOP) language. Referencing a class declaration, an instantiated object is named and created, in memory or on disk.


1 Answers

There may be other reasons but in VB6 using the New keyword when you Dim an object can cause unexpected results because VB will instantiate the object whenever it is referenced.

Dim objMyObject as New SomeObject

Set objMyObject = Nothing   ' the object is nothing

If objMyObject Is Nothing Then  ' referencing the object instantiates again
   MsgBox "My object is destroyed"  ' what you would probably expect
Else
   MsgBox "My object still exists"
End If
like image 151
jac Avatar answered Oct 02 '22 09:10

jac