is operator overloading in fact polymorphism or parameter overloading?
Is it true that polymorphism usually refer to different classes responding to the same "message" (the method name) and do different things, so
bird.give_sound()
and
car.give_sound()
can do different things. And parameter overloading is more about talking about the same class, doing different things when the parameters sent along with the message (the method name) are different. So
bird.give_sound()
and
bird.give_sound(:frighten_sound)
can be different.
So operator overloading is strictly parameter overloading? like this following:
"foo" + "bar"
"foo" + 3
at least in Ruby, it is sending the +
message to the string containing foo
, the first line is sending with a parameter string, the second one is sending a parameter 3, and the +
do slightly different things, but it is the same receiver class String
In the following example, it is polymorphism:
"foo" + 3
1 + 3
because the +
message invoke different methods of different classes, but using the same message name +
. So in these 2 cases, they are polymorphism, not operator overloading?
Is the above accurate and correct? Is there something that might be added to it or be corrected above?
Thank you for the clarification of context in your comment. Yes, I would say you are correct.
To summarize as short as possible...
Given identical method name (or "message"):
I'm going to take a stab in the dark and say that it's kind of (but not really) both.
Each object has to deal with the given object (the object on the right side of the operator) in a specific way. With strings, it seems that the toString
method (or other language equivalent) would be used. So you would always be appending a string (passed to the method as an Object
). (Polymorphism)
However, your object may need to perform different logic based upon the object given. For example, say you have a Student
object. You may have one version of the method that takes a Class
object, and adds it to the Student's class schedule. You then might have an overload that takes, say, a Book
and adds it to the Student's collection of required reading material. (Parameter Overloading)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With