Function overloading program

give me some real life based examples of function overloading

If you are asked to calculate the aggregate for your class X and class XII, you can find that out by adding the marks of all your subjects and dividing it by the number of subjects you had.
In case of class X, the subjects you take would be more than those in case of class XII. (In India at least, this is the case). Now you see, the parameters you take for your function (to calculate the aggregate in both cases) are different, but you calculate the same thing - aggregate.
For mnemonics, aggregate (or calc_aggregate) would be the appropriate name for this function, but its arguments differ in both cases.

1 Like

Suppose your room is dirty and you have to clean it. Suppose there are pieces of food lying on your floor, and also you have dropped soft drinks on the floor to make it sticky. You need to do the same thing - clean the room. But you have to perform both the cleaning processes differently. One using a broom or a vacuum cleaner, other using a damp cloth.

Both require different implementations, and it would be desirable to give them both the same name: clean.

Function overloading : Same name with change in parameter type,Number of parameters or change in order of parameter types.

Function overloading helps to give different functionality(implementation) for different cases as i discussed above.

Function overloading actually helps user to remember the name of a function and use it easily in different cases, otherwise we could have used different function name rather than same.

Real Life example : Suppose you want to send mail to friend/friends at this time you can overload function send() like

case 1: You need to send mail to one of your friend send(toaddress,subject,body)

case 2: You need to send mail to two friends send(toAdd1,toAdd2,sub,body)

case 3: Mail with attachment send(toAdd,sub,body,attachment)

Suppose you have two function with same name but different arguments named…LikesToDo(Girl object), LikesToDo(Boy object), where Boy and Girl are the two different classes. Now, body of the functions:

LikesToDo(Girl object)
Go to school;
Go to Library;
if not reached maximum book limit then takes a book;
else return an old book and get a new book;

LikesToDo(Boy object)
Go to school;
Go to the playground;
If not raining then play outdoor games;
else play indoor games;

Now, suppose caller function calls LikeToDo(Ramesh), Now which body of the function get invoked depends on which class the object Ramesh belongs to, If it belongs to Girl class then the first body get invoked if it belongs to boy, then second body gets invoked.