Cool Visual Basic
 
Main
Frequently Asked Questions
VB Helpdesk
Message Boards
Library
Downloads
View Guestbook
Add to Guestbook
Product Reviews
Bookstore
Links
Newsgroups
Vendors
Affiliates
Cooltech.org

Theoretically, you can't overload operators in VB. However, in fact, that rule is easy to break(to a degree) with the assistance of these factors:

  • You can set the default property for a class
  • Strings can be concatenated with the + or the & operators
  • Variants can hold any kind of object or variable

With this in mind, check this out:

Private mvarValue As String 'local copy
Public Property Let Value(ByVal vData As Variant)
 Dim i As Integer, j As Integer, x As Integer, l As Integer
 Dim exitflag As Boolean
        If VarType(vData) = vbString Then
                If InStr(vData, " ") Then
                i = 1
                j = 1
                i = InStr(1, vData, " ")
                  Do While InStr(i, vData, " ")
                    j = i
                    i = InStr(j + 1, vData, " ")
                    If i = 0 Then i = (Len(vData) - i) + 1: exitflag = True
                    x = CInt(Mid$(vData, j + 1, i - (j + 1)))
                    l = x + l
                    If exitflag Then Exit Do
                  Loop
                  mvarValue = " " + CStr(l)
                Else
                  mvarValue = " " + CStr(vData)
                End If
        ElseIf VarType(vData) = vbDecimal Then
                mvarValue = " " + CStr(vData)
        End If
End Property


Public Property Get Value() As Variant
    Value = mvarValue
End Property

Before you do anything with this class, you must follow these steps:

  • Go into object browser.
  • Find the class you put this code in.
  • Select Value.
  • Right-click value and click properties.
  • Click Advanced.
  • Set the Procedure ID to "(Default)".

At this point, you might be a bit confused. Basically, what I've done is made the property value default. So when you say I = 3 it understands that you mean I.Value = 3.

Next, I've made I a variant. So, you can pass I.Value = "3" or I.Value = 3.

Finally, I've made the Property Get for value pad it with a space.

As a result, you have faked operator overloading. Admitedly, this is not the most useful ability - it is, however, a rather strange artifact.


Copyright 2006, David J Berube<Form1@coolvb.com>. All Rights Reserved.