Operator Overloading C++ | Sololearn: Learn to code for FREE!


Operator Overloading C++

Can someone explain a real world example where I would need to overload an operator? Can you please also explain to me what exactly overloading sn operator is?

4/16/2018 12:04:53 PM

Eryl Deverton

7 Answers

New Answer


To overload an operator, you need a class that has data that makes sense to have an overloaded operator. A good example would be implementing a bigger integer than 'long long'. You could implement it as a string with values 0 to 9 in the characters using a -1 as the sign bit. Ignoring the class structure and methods for the moment lets you do this: class mylong {} result, first, second; result = first + second; In mylong, you would declare the operator+ method, which would loop through the strings adding digits.


Sandin Jayasekera you're welcome. If I had a decent example, I'd show you. But, mine are in Python and Kotlin only.


Sandin Jayasekera I converted my Kotlin example to C++. It isn't a good class example as there is no reason for it to exist except to play with operators. However, it demonstrates all integer math operations. https://code.sololearn.com/cStdw0OPtPxG


John Wells I'm going to have to do some more research on this topic, I still have trouble understanding what exactly overloading an operator means... thanks for the help though.


Operator overload: Let’s say you have a class with X and Y coordinates. With an object of this class, I’d like to plot the next point in a line that runs 45 degrees from the X axis. This means I need to increase both my X value and my Y value by 1. I could write a function, or if I plan to do it multiple places, I could override the increment operator. This is pseudo code because I haven’t been in c++ for 20 years and I am no longer familiar with the syntax Declare a new instance of the class Point called myPoint; myPoint.X=1; myPoint.Y=1; myPoint.print ;//(class method to display the plotted point on a graph on the screen) //Prints a Point 2 step diagonally up to the right from the cross-hairs myPoint++; //overloaded operator execute the equivalent of myPoint.X= myPoint.X+1; myPoint.Y= myPoint.Y +1; myPoint.Print; //Prints a Point 2 step diagonally up to the right from the cross-hairs Now let’s declare a new instance of Point called ‘target’ target.X=2; target.Y=2; If (myPoint == target ) then cout << “It’s a hit” //this won’t function as you would like, unless you overload the ‘==‘ operator to check if each X value of the two objects are equal and if the two Y values of the object are equal. Let me know if I can provide any more clarification.


Aidos Zhakupov I can't really understand that, could you please explain it in idiot terms? I'm pretty new to this.