Saturday, May 22, 2010

Can someone explain overloading?

I'm taking the final version of the C++ course offered by my jr college, and up to this point I have had almost no trouble understanding and implementing what I've learned in class and in my book, however I'm having a hard time understanding overloading, weither be it function, or operator (espically operator).





I am not looking for a textbook def, or a google define, or anything of the sort. My main questions are what I'm having a hard time understanding.





1)My text book says that operator overloading does not allow the programmer to create NEW operators, but extend the def of pre-exisitng ones. I dont see how this is very useful being as the examples in the book (where the overloading functions are defined {take + as an example} are comparing data members such as the example below})





int operator+(const class1%26amp; obj1, const class1%26amp; obj2)


{


class1 objtemp;


objtemp = obj1.length + obj2.length;


return value;


}





The rest will posted in an addiontal detail, I am out of space.

Can someone explain overloading?
As you have already figured out, operator overloading simply allows the developer to define custom functionality for a given operator (such as +, -, /, *, etc.). I have found this is mostly useful in performing math-like operations on objects. For example: you're working on a payroll application and you have two objects that represent an employee's last two paychecks (class paycheck). Since the objects are really pointers, simply adding the two objects together would likely add the two addresses they exist at together. However, by overloading +, you can have one of the two objects add the other objects values (like gross income, taxes, vacation hours, medical expenses, and net income) to itself.
Reply:Operators are ALREADY overloaded to begin with. The concept is simply extended so programmers can do more of it. For example, you can use the "+" operator on integers, floats, doubles, and strings! So it is already overloaded, in other words, it operates differently depending on the kind of objects it operates on.





This can be misused, but it is intended for situations where it makes sense to reuse the "+" operator. Of course, you can overload it to do any thing and if you make a poor choice then it will make the program more difficult to read. A good choice will make it easier to read.





This is associated with the concept of "polymorphism".

gladiolus

No comments:

Post a Comment