According to wiki:
In programming, operator overloading, sometimes termed operator ad hoc polymorphism, is a specific case of polymorphism, where different operators have different implementations depending on their arguments. Operator overloading is generally defined by a programming language, a programmer, or both.
In other words, you can add your own functionality to operators of your objects, i.e.:
cat1 + cat2
I wanted to play with this idea of making Animal objects and overloading the operators to do so fun things. So I had to make classes for my animals:
Now that I can make cat and dog objects, I thought that when you add two animals together it should do this:
animal1 + animal2 "animal2 is animal1's best friend" animal1.best_friends [<Cat name: animal2 >]
When you have animal1 and then you bring in animal2, they’ll become best friends. But if animal1 is cranky or very unfriendly and you bring in animal2, animal1 may think that they are mortal enemies for coming around them.
The fun part was figuring out what happens when you multiply animals!
litter = dog1 * dog2 litter [<Dog name:'bob'>, <Dog name:'jill'>]
First I had to check if the two objects are the same species and if they are, then I generate a random number for the size of their littler. Then I loop over the range of the random number, creating a new instance of the parent’s class and returning all the instances in a list!
I’ve been working on this on the side for a day or two and I’ve had a blast. Check out a quick video from DevelopHerDevelopHim for a walk through the code below!
Check out my code on github and make your own cats, dogs, pandas, hamsters, rabbits, frogs, monkeys, mice and fish!