Learn C++
#include "functions/function_overloading.hpp"

Function Overloading in C++

//concept

Overloading lets several functions share one name as long as their parameter lists differ — print(int), print(double), print(string) are three distinct functions the compiler tells apart at each call. It expresses one idea (print, max, construct) across types without inventing printInt/printDouble clutter.

Resolution picks the best viable match, preferring exact types over promotions over conversions; ambiguous calls (equally good matches) fail to compile rather than guess. Return type alone never distinguishes overloads — parameters must differ in count, type, or order.

//how it works
1

Same name, different params

Overloads differ by arity or parameter types. The compiler mangles each into a unique internal symbol behind the scenes.

2

Best match wins

Exact type beats promotion (short to int) beats conversion (int to double). The ranking is deterministic, not heuristic.

3

Ambiguity is an error

Two equally good candidates make the call ambiguous — the compiler rejects it instead of picking arbitrarily.

4

Return type doesn't count

int f() vs double f() with identical parameters is a redefinition error — callers can't always use the result, so it can't disambiguate.

//example
#include <iostream>
 
int max2(int a, int b) { return (a > b) ? a : b; }
double max2(double a, double b) { return (a > b) ? a : b; }
 
int main() {
std::cout << max2(3, 7) << std::endl;
std::cout << max2(3.5, 2.5) << std::endl;
return 0;
}
Output
7
7
1max2(3, 7) matches the int overload exactly — no conversion needed.
2max2(3.5, 2.5) matches the double overload exactly, preserving the decimals.
3One name served both call sites; the compiler dispatched each statically with zero run-time cost.
//use cases
One print/log/display name across every supported type
Constructors offering several initialization styles for one class
max/min/abs-style utilities that must preserve int vs double exactly
API evolution: adding an overload with extra parameters without breaking old calls

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.