DEV Community

loading...
Cover image for Function Overloading in C++

Function Overloading in C++

blender profile image Saloni Goyal Updated on ・2 min read

One of the cool things about C++ is that function names don't always have to be unique.

As long as the compiler can tell the two functions apart, you can have functions with the same name and this is called overloading.

In C++, there is no need to twist names to include parameter information.

Taking different number of arguments is a great way to distinguish overloads

Alt Text

It is common to have one overload of the function call another overload of the function.

Return type can never be used to distinguish overloads

You can overload on parameters, you can't overload on return types.

You don't have to use the return value of a function if you don't want to.

add(3,2); // works

This is why we can't overload on return type. If you have two functions that take the same type of parameters but have different return types and you put in a line of code where you call the function but don't use the return type for assignment, the compiler would be unable to decide which function to use.

Taking the same number of arguments, but of different type can be risky

Alt Text

  • here argument passed is 'int'
  • to the compiler the call could be to bool test(double) or to bool test(bool).
  • there is no overload of test which takes int, compiler needs to convert int to a valid argument
  • and since it knows both how to convert an int into a double as well as to convert an int into a bool (value 0 is considered as false, rest all are considered to be true), the compiler doesn't know what to choose.

Possible solution:

  • explicitly convert the int to a double or a bool.
  • write another overload function of test that takes integer parameters.

Please leave out comments with anything you don't understand or would like for me to improve upon.

Thanks for reading!

Discussion (0)

pic
Editor guide