What is function overloading? When do we need to use it?

In C++, Single function name can be use to perform different types of tasks, this is
known as function overloading.


Format of overloaded function includes:
1. Number of arguments
2. Type of arguments
3. Sequence of arguments
When you call an overloaded function, the compiler determines the most appropriate
function definition to use by comparing the format of calling statement with the function
format specified in the definitions.

c++ allows function overloading.that is ,we can have more than one function with the same name in our program. the compiler matches the function call with the exact function code by checking the number and type of the arguments.

a function call first matches the prototype having the same number and type of arguments and then calls the appropriate function for execution. a best match must be unique.the function selection involves the following steps

  1. the compiler first tries to find an exact match in which the type of actual argument are          the same adn use that function

   



Example of function overloading: this program prints the given

character for a given number of times. Here function repchar() is
overloaded.


#include<stdio.h>

#include<conio.h>

#include<iostream.h>

class r1

{

public:

void repchar();

void repchar(char ch);

void repchar(char ch,int n);

};

void r1:: repchar()

{

int i,num;

char ch;

cout<<"enter the character"<<"\n";

cin>>ch;

cout<<"how many times"<<"\n";

cin>>num;

for(i=0;i<=num;i++)

{

cout<<ch;

}

}

void r1::repchar(char ch )

{

int i,num;

cout<<"how many times"<<"\n";

cin>>num;

for(i=0;i<=num;i++)

{

cout<<ch;

}

}

void r1::repchar(char ch,int n)

{ int i;

for(i=0;i<=n;i++)

{

cout<<ch;

}

}

void main()

{

clrscr();

char ch='S';

r1 r;

r.repchar();

r.repchar(ch);

cout<<endl;

r.repchar(ch,10);

getch();

}


Post a Comment

If you have any doubts, Please let me know
Thanks!

Previous Post Next Post