What is operator overloading.. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What is operator overloading..

10th Sep 2016, 6:32 AM
khushboo kotadia
khushboo kotadia - avatar
4 Answers
+ 6
Operator overloading allows you to use operators like +, -, *, etc. with custom classes. Example: http://code.sololearn.com/cbJlO8tA1Luv class Complex: re = 0 im = 0 def __init__(self, re=0, im=0): self.re = re self.im = im def __str__(self): return "({0},{1})".format(self.re, self.im) def __add__(self, other): re = self.re + other.re im = self.im + other.im return Complex(re, im) def __mul__(self, other): re = self.re * other.re - self.im * other.im im = self.re * other.im + self.im * other.re return Complex(re, im) def __eq__(self, other): return self.re == other.re and self.im == other.im c1 = Complex(1, 2) c2 = Complex(3, 4) print(c1 + c2) print(c1 * c2) print(c1 == Complex(1, 2))
10th Sep 2016, 9:01 AM
Zen
Zen - avatar
+ 2
operator overloading is like operator performing multiple tasks eg + in Python can add numbers as well as concatenate strings. The result of such operator depends on it's argument😀
10th Sep 2016, 7:11 AM
Akhil Gaur
Akhil Gaur - avatar
+ 2
operator overloading means performing coustamised tasks using operators eg + operator can be overloaded to perform addition of tuples also it can be used for subtraction after proper overloading
10th Sep 2016, 7:18 AM
Chirag Rade
Chirag Rade - avatar
+ 1
Thanks for the ans....
10th Sep 2016, 7:34 AM
khushboo kotadia
khushboo kotadia - avatar