Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In OOP, is operator overloading in fact polymorphism or parameter overloading?

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?

like image 918
nonopolarity Avatar asked Mar 28 '11 13:03

nonopolarity


2 Answers

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"):

  • different behaviour based on parameter type is overloading,
  • different behaviour based on object type is polymorphism.
like image 53
DevSolar Avatar answered Oct 03 '22 17:10

DevSolar


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)

like image 27
FreeAsInBeer Avatar answered Oct 03 '22 16:10

FreeAsInBeer