Home >>VB.Net Built-in Functions >VB.Net program to overload binary multiplication (*) operator

VB.Net program to overload binary multiplication (*) operator

Write a VB.Net program to overload binary multiplication (*) operator

Here, in order to get the remainder, we can overload the binary multiplication (*) operator with a class to apply multiplication operations between two objects.

Program :

Below is the source code for overloading the binary multiplication (*) operator. The program given is compiled and successfully executed.

'VB.net program to overload binary multiplication "*" operator.


Class Sample
    Dim num1 As Integer
    Dim num2 As Integer
    Sub SetValues(ByVal n1 As Integer, ByVal n2 As Integer)
        num1 = n1
        num2 = n2
    End Sub
    Public Shared Operator Mod(ByVal S1 As Sample, ByVal S2 As Sample) As Sample
        Dim temp As New Sample()
        temp.num1 = S1.num1 * S2.num1
        temp.num2 = S1.num2 * S2.num2
        Return (temp)
    End Operator
    Sub PrintValues()
        Console.WriteLine(vbTab & "Num1: {0}", num1)
        Console.WriteLine(vbTab & "Num2: {0}", num2)
    End Sub
End Class
Module Module1
    Sub Main()
        Dim obj1 As New Sample()
        Dim obj2 As New Sample()
        Dim obj3 As New Sample()
        obj1.SetValues(6, 4)
        obj2.SetValues(3, 7)
        obj3 = obj1 Mod obj2
        Console.WriteLine("Obj1: ")
        obj1.PrintValues()
        Console.WriteLine("Obj2: ")
        obj2.PrintValues()
        Console.WriteLine("Obj3: ")
        obj3.PrintValues()
    End Sub
End Module
	
Output:
Obj1:
Num1: 6
Num2: 4
Obj2:
Num1: 3
Num2: 7
Obj3:
Num1: 18
Num2: 28
Explanation:

We have created a Sample class in the above program, which includes two SetValues(), PrintValues() methods to set and print the values of the data members of the class. Here, we have introduced another way of overloading the binary multiplication (*) operator.

After that, we built a Module1 module that contains the Main() method, and the program entry point is the Main() method. And, the two objects of the Sample class have been created and then the binary multiplication operation is done between two objects, returning the multiplication that is assigned to the third object.


No Sidebar ads