| I am still curious, why the below code throws error.
|
I see what you mean. I didn't realize that making it
the default function was an important part of what you
wanted to do.
This works as expected:
'------------------------------------------------
Set myInstance = New myClass
MsgBox myInstance
Class myClass
Public Default Function GetTime()
GetTime = Now()
End Function
End Class
'--------------------------------------------------
It returns the current time.
This doesn't work:
Set myInstance = New myClass
Set Dic = MyInstance
MsgBox Dic.Count
Nor this:
Set myInstance = New myClass
MsgBox myInstance.count
"By law" it should work, but the result makes sense.
In both versions the object referenced is ambiguous.
If the default function returns an object then there's
no way to reference the original object!
For instance, if you could do:
Set myInstance = New myClass
MsgBox myInstance.count
Then you wouldn't be able to do:
x = myInstance.Method2
WSH would report an error because Dictionary has
no Method2 function.
It's not for me to say how you should code, but I
think you'll find that most people avoid default methods.
They don't save any appreciable work but do cause
a lot of confusion, and they're only usable at all when
both the author and anyone working with the code later
are familiar with the object methods.
In VB6 there is a similar option and all controls have
default methods. The default property of a Textbox is
Text. That's the only one I know. :) Because in 12+ years
of using VB6 I've never used default methods/properties.
If I did I'd have to always study the context when an
object variable is used alone, to see whether it references
the object or the default property. To what purpose? I only
achieve the ability to avoid typing the word "text".