Function Overloading in C/C++

Function overloading or method overloading is a feature found in various programming languages such as Ada, C++, C#, D, and Java, that allows creating several methods with the same name which differ from each other in the type of the input and the output of the function. It is simply defined as the ability of one function to perform different tasks.

For example, doTask() and doTask(object O) are overloaded methods. To call the latter, an object must be passed as a parameter, whereas the former does not require a parameter, and is called with an empty parameter field. A common error would be to assign a default value to the object in the second method, which would result in an ambiguous call error, as the compiler wouldn't know which of the two methods to use.



Below is a  Program which calls a function for string input from the user (like the in-built getline() function)
Ask the user to input the size of the string ( negetive for none ) and delimiter of the string ('n' for none).
If size is negetive call function myGetline(buf, del) with default size 80.
If size is given, delimiter is not gives, calls function myGetline(buf, size) with default delimiter 'n'.
If both are not given calls function myGetline(buf) with default size 80 and delimiter 'n'.



#include<iostream>
using namespace std;
class myGetlineFun
{
public:
 void myGetline(char buf[], char del);
 void myGetline(char buf[], int size);
 void myGetline(char buf[]);
};
void myGetlineFun::myGetline(char buf[], char del)
{
 for (int i = 0; i < 80; i++)
 {
  if (buf[i] == del)
  {
   cout << "\n";
   break;
  }
  else
  {
   cout << buf[i];
  }
 }
}
void myGetlineFun::myGetline(char buf[], int size)
{
 for (int i = 0; i < size; i++)
 {
  cout << buf[i];
 }
 cout << "\n";
}
void myGetlineFun::myGetline(char buf[])
{
 for (int i = 0; i < 80; i++)
 {
  if (buf[i] == '\n')
  {
   cout << "\n";
   break;
  }
  else
  {
   cout << buf[i];
  }
 }
}
int main()
{
 myGetlineFun obj;
 char name[80], dl;
 int sz;
 cout << "Enter String -> ";
 cin >> name;
 cout << "Enter Size -> ";
 cin >> sz;
 cout << "Enter Delimeter ->";
 cin >> dl;
 
 cout << "String Is -> ";
 
 if (sz<1)
 {
  obj.myGetline(name, dl);
 }
 else if (sz>0)
 {
  obj.myGetline(name, sz);
 }
 else
 {
  obj.myGetline(name);
 }
 return 0;
}

Post a Comment