Function Overloading in C++

C++ supports overloading of function names and operators for both user defined types and built in types.For Example we can create several functions named print, or we could overload the “+” operator to work for a new type. In C++ , a function name is overloaded by simple declaring (and defining)several functions with that name.

 

For Example:

Void print(char *);

Void print(double);

Void print(int);

If several functions have the same name, it must be possible for the compiler to select among them based on the number and type of arguments and the type of invoking object(for member functions). This means that the overloaded functions should not have the same argument list. Once these functions have been declared and written, we can rely on the compiler to call the correct one.

Example:

   #include<conio.h>

#include<iostream.h>

#include<stdio.h>

#include<string.h>

int max_string_length=128;

class string

{

public:

   void set_to(char *);

   int length();

   void read();

   void print();

string concat(string *);

string concat(char *);

private:

char text[max_string_length+1];

};

string string::concat(string *other)

{

string both;

strcpy(both.text,text);

strcat(both.text,other->text);

return both;

}

string string::concat(char *ptr)

{

string both;

strcpy(both.text,text);

strcat(both.text,ptr);

return both;

}

int string::length()

{

return strlen(text);

}

void string::read()

{

gets(text);

}

void string::print()

{

puts(text);

}

void string::set_to(char *str)

{

strcpy(text,str);

}

void main()

{

string firstname,lastname,name;

firstname.set_to("XCnotes");

lastname.set_to(".com");

name=firstname.concat(" ");

name=name.concat(&lastname);

name.print();

return 0;

getch();

}

Function Function in C++

Explanation…

In this example concat function is overloaded. When a pointer to a string object is passed then concat(string *other) function is called. When a pointer to a character string is passed then concat(char *ptr) function is called.

Overloading is important for several reasons. Overloading lets the author of a function concentrate on choosing a name that accurately and concisely describes what the function does(instead of a name that shows what type of argument the function takes). It also simplifies the job of using the function or operator. For example if you need a function to find out the minimum of two integers and another function to find out the minimum of two floating numbers, without overloading both these functions should have different names. With overloading both these functions can have the same name as, their argument list differs. Without overloading, it may be difficult to write software that uses several libraries, if those libraries contain functions with the same name. If such functions work with different types of arguments and our language supports overloading we can use both functions without a problem.