Page 1 of 1

Operator Overloads Make your Object know basic Math, Rate Topic: -----

#1 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2216
  • View blog
  • Posts: 9,352
  • Joined: 29-May 08

Posted 05 March 2010 - 08:32 PM

Note: I have use vb.net 2010 in this Tutorial but it is applicable to vb.net 2008
Operator Overloading.

Operator Overloads let redefine the meaning of particular operators.
The over-ridable operators are;
Mathematical Operators: + - * / \ ^ Mod
Comparison Operators: < > = <> <= >= IsTrue IsFalse
Logical Operators: And Or Not Xor
CType Operators:
Narrowing CType
Widening CType
Shift Operators: >> <<
String Operator: &

Example: Angle Class
Suppose we define a class to contain an angle in Degrees, with a value (0<= a <360).
Now we want to calculate what the result of result of the following equation.
A=90
B=45
C=270
T=(A-B)+C

Public Class Angle
    Protected mAngle As Decimal = 0
    Public Sub New(Optional ByVal Angle As Decimal = 0)
        Me.Angle = Angle
    End Sub
    Public Property Angle() As Decimal
        Get
            Return mAngle
        End Get
        Set(ByVal value As Decimal)
            mAngle = value
            Normalise()
        End Set
    End Property

    Private Sub Normalise()
        mAngle = mAngle Mod 360
    End Sub
    Shared Function Add(ByVal aA As Angle, ByVal aB As Angle) As Angle
        Return New Angle(Angle:=aA.Angle + aB.Angle)
    End Function
    Shared Function Subtract(ByVal aA As Angle, ByVal aB As Angle) As Angle
        Return New Angle(Angle:=aA.Angle - aB.Angle)
    End Function
    Public Overrides Function ToString() As String
        Return String.Format("{0}", mAngle)
    End Function
End Class


So with above version of the angle class (without operator overloads) to implement the equation we would have to use function calls.
Dim T = Angle.Add(Angle.Subtract( A , B ) , C )


Note that we have to write the addition first than the subtraction. Plus it is getting rather hard to tell the meaning of the code. Imagine if the equation was longer.


Using Operator Overloads
To enable use to write the equation as written we need to add in the operator overloads to the Angle class.
Public Class Angle
    Protected mAngle As Decimal = 0
    Public Sub New(Optional ByVal Angle As Decimal = 0)
        Me.Angle = Angle
    End Sub
    Public Property Angle() As Decimal
        Get
            Return mAngle
        End Get
        Set(ByVal value As Decimal)
            mAngle = value
            Normalise()
        End Set
    End Property

    Private Sub Normalise()
        mAngle = mAngle Mod 360
    End Sub

    Shared Operator +(ByVal aA As Angle, ByVal aB As Angle) As Angle
        Return New Angle(Angle:=aA.Angle + aB.Angle)
    End Operator
    Shared Operator -(ByVal aA As Angle, ByVal aB As Angle) As Angle
        Return New Angle(Angle:=aA.Angle - aB.Angle)
    End Operator
    Public Overrides Function ToString() As String
        Return String.Format("{0}", mAngle)
    End Function
End Class


So now it much easier to write the equation.
Dim T = (A-B) + C



Is This A Good Question/Topic? 0
  • +

Replies To: Operator Overloads

#2 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2216
  • View blog
  • Posts: 9,352
  • Joined: 29-May 08

Posted 07 March 2010 - 02:17 PM

Example 2: My Party.
What is a Party? A Party is a collection of people celebrating.

So let define our collection for a group of people.

Public Class GroupOfPeople
 Protected Friend People As New List(Of Person)

#Region "New's"
 Public Sub New()

 End Sub

 Public Sub New(ByVal ThisGroup As GroupOfPeople)
  People.AddRange(ThisGroup.People)
 End Sub
 Public Sub New(ByVal ThesePeople As Person())
  People.AddRange(ThesePeople)
 End Sub
 Public Sub New(ByVal ThesePeople As IEnumerable(Of Person))
  People.AddRange(ThesePeople)
 End Sub
#End Region

 Public Function Males() As IEnumerable(Of Male)
  Return Me.People.OfType(Of Male)()
 End Function
 Public Function Females() As IEnumerable(Of Female)
  Return Me.People.OfType(Of Female)()
 End Function
End Class




From the above section of code you will note that there are three missing classes. Person, Male & Female
A Male is a type of Person.
A Female is also a type of Person.

So you can tell that Male and Female must inherit from a common base type Person, and you'll be right.

Class: Person
Public MustInherit Class Person
 Protected mName As String = ""
 Public ReadOnly Property Name As String
  Get
   Return mName
  End Get
 End Property

End Class



Class: Male
Public Class Male
 Inherits Person

 Public Sub New(ByVal Name As String)
  mName = Name
 End Sub
End Class



Class: Female

Public Class Female
 Inherits Person

 Public Sub New(ByVal Name As String)
  mName = Name
 End Sub
End Class





OK What about the Operators?
Partial Public Class GroupOfPeople
 Shared Operator +(ByVal ThisGroup As GroupOfPeople,
                ByVal ThisPerson As Person) As GroupOfPeople
  ' Adds Person (ThisPerson) into the GroupOfPeople (ThisGroup)  '
  Return New GroupOfPeople(ThisGroup.People.AsEnumerable.Concat(Enumerable.Repeat(ThisPerson, 1)))
 End Operator
 Shared Operator -(ByVal ThisGroup As GroupOfPeople,
   ByVal ThisPerson As Person) As GroupOfPeople
  ' Removes Person (ThisPerson) into the GroupOfPeople (ThisGroup)  '
  Return New GroupOfPeople(ThisGroup.People.AsEnumerable.Except(Enumerable.Repeat(ThisPerson, 1)))
 End Operator
End Class


So now you can see that we can add and subtract (Remove) a Person, whether they are Male or Female because they inherit from Person.
Dim MyParty As New GroupOfPeople
MyParty += New Male("Adam")



But if you try to do
 Dim MyParty As New GroupOfPeople
  Dim Adam As New Male(Name:="Adam")
  Dim Mark As New Male(Name:="Mark")
  Dim Laura As New Female(Name:="Laura")
  MyParty = Adam + Mark + Laura


You get an Error
Error 1 Operator '+' is not defined for types 'ConsoleApplication1.Male' and 'ConsoleApplication1.Male'. C:\Users\Adam Speight\documents\visual studio 10\Projects\OperatorOverload_TheParty\OperatorOverload_TheParty\Module1.vb 8 13 OperatorOverload_TheParty


What's the Solution?
If you are follow this you may have already have guessed at a solution, have if it is just an idea.

Since the type GroupOfPeople knows howsto add a person to it; Thus when we do
Person (Adam) + Person (Mark)

We return a GroupOfPeople which contains the two Peopleinstances (Adam & Mark).
So when we come to add the third Person (Laura) that the addition is taken care of by the + operator in the GroupOfPeople Class.

And you be correct.

Partial Public MustInherit Class Person

 Shared Operator +(ByVal ThisPerson As Person,
                    ByVal AndThisPerson As Person) As GroupOfPeople
  Return New GroupOfPeople(Enumerable.Repeat(ThisPerson, 1).Concat(Enumerable.Repeat(AndThisPerson, 1)))
 End Operator

End Class



So when we try to do it compiles and works.
 Dim MyParty As New GroupOfPeople
  Dim Adam As New Male(Name:="Adam")
  Dim Mark As New Male(Name:="Mark")
  Dim Laura As New Female(Name:="Laura")
  MyParty = Adam + Mark + Laura




Review
Operators can be implemented in the base class of a type to save on code duplication.
Operators can return a type different to the one are in. Eg. Person + Person -> GroupOfPeople.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1