ReviseAlgo Logo

Functions

Function Overloading

Multiple functions with same name

Interview: Polymorphism concept

Function Overloading

C++ allows multiple functions with the same name but different parameter lists. The compiler selects the correct overload at compile time based on the types and number of arguments — a process called overload resolution.

Overload Resolution Rules

The compiler ranks candidates: exact match > standard promotion (int to long) > standard conversion (int to double) > user-defined conversion. If two candidates are equally good, the call is ambiguous (compile error).

What Cannot be Overloaded

Overloading by return type alone is not allowed — the compiler cannot determine which overload to call based only on how the result is used. Parameter names and default values also don't distinguish overloads.

Interview Corner

Q: How does name mangling relate to function overloading?

A: C++ compilers encode function parameter types into the symbol name in the object file — called name mangling. void f(int) and void f(double) become different mangled names (e.g., _Z1fi and _Z1fd on GCC). This is why overloading works at the linker level. C doesn't mangle names, which is why C functions need extern "C" in C++ headers.

Common Pitfalls

  • Ambiguous overloads: Calling f(0) when both f(int) and f(long) exist creates an ambiguity error.
  • Hiding base class overloads: Defining a function with the same name in a derived class hides ALL base class overloads with that name, not just the matching one.

Best Practices

  • Use overloading when functions logically do the same thing for different types. Use different names when the operations are semantically different.
  • Prefer function templates over overloads when the body is identical for all types.