DEV Community

Igor
Igor

Posted on

Overloading Functions

  • We can have functions that have different parameter lists that have the same name
  • This is a great use of abstraction since as a developer all i need to think is display and pass in whatever information i need. I don’t have to keep track of dozens of different function names.
  • In SWE, we have a principal called polymorphism, which means many forms for the same concept. This is an example of polymorphism.
int add_numbers(int, int);           // add ints
double add_numbers(double, double);  // add doubles

int main()
{
    cout << add_numbers(10,20) << '\n';       // integer    
    cout << add_numbers(10.0,20.0) << '\n';   // double
    return 0;
}
Enter fullscreen mode Exit fullscreen mode
  • The parameter list for these functions must be different so the compiler can tell them apart. Once these functions are implemented, I can call display and pass in my data. The compiler will check the type of the argument in the function and match it to one of the available overloaded display functions.
void display(int n);
void display(double d);
void display(std::string s);
void display(std::string s, std::string t);
void display(std::vector<int> v);
void display(std::vector<std::string> v);
Enter fullscreen mode Exit fullscreen mode
  • If it can’t match it or if it can’t convert the argument to one that matches, then we get a compiler error.
  • Important - There is one restriction to function overloading. The return type is not considered when the compiler is trying to determine which function to call.
int get_value();
double get_value();

// Error
cout << get_value() << '\n';  // which one?
Enter fullscreen mode Exit fullscreen mode
  • Here we have two overloaded functions, both called get_value and both expect no parameters. The only difference is that one returns an integer and the other a double. This will produce a compiler error since the only difference is the return type.
  • Overloading function is used extensively in object-oriented design.

Top comments (0)