What is function overloading ? Why is it needed ? Or What is function overloading ? How polymorphism is achieved by function overloading ?

What is function overloading ? Why is it needed ? Or What is function overloading ? How polymorphism is achieved by function overloading ?

Ans. Function overloading is a mechanism that helps  us to get compile-time polymorphism. It means one interface and many methods.

When we overload the function, we can use the same function name to create function that perform a varietyof different tasks. This is possible because C++ permits the use of same name by two or more functions, provided the type of their argument differs or number their arguments differs or both differ. This is known as function polymorphism in OOP.

Function overloading is needed because, by this, we can design a family of function with one  function name but with different argument list. The function would perform different operations depending on the argument list in the function call. the correct function to be called is determined by checking the number and type of the arguments but not on the function typ.

A function can be overloaded by declaraing and defining all the required versions. The compiler selects the correct version based on the number and type of  arguments used at the time of function call.

For example,

#include <iostream.h>

#include <math.h>

Int sqroot (int);

Long sqroot(long);

Double sqroot(double);

Int main ( )

Int a = 15;

Long b = 360;

Double c = 120.63;

Cout <<”n Integet square root : “ <<sqroot (a) ;

Cout <<”n Long integer square root :”<<sqroot (b);

Cout <<”n Doublen square root : “<<sqroot (c);

}

Int sqroot(int i)

{

Return(int) sqrt ((double) i));

}

Long sqroot(long)

{

Return(long) sprt ((double)));

}

Double sqroot(double x)

{

Return sprt(x);

}

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *