In the Functions chapter, every function had its own unique name. Now suppose you want a function that prints a value. In C you would need printInt, printDouble, printChar… one name per type. That is tiring to write and even more tiring to remember.
C++ lets several functions share the same name, as long as their parameter lists are different. The compiler looks at the arguments of each call and picks the right one.
Function overloading means defining two or more functions in the same scope with the same name but different parameter lists (different number, types or order of parameters). The compiler chooses which one to call at compile time, based on the arguments.
Because the choice is made while compiling, overloading is a form of compile-time (static) polymorphism: one name, many forms. (Run-time polymorphism with virtual functions comes much later, in Polymorphism & Virtual Functions.)
A First Example
#include <iostream>
void print(int x) { std::cout << "int: " << x << '\n'; }
void print(double x) { std::cout << "double: " << x << '\n'; }
void print(char x) { std::cout << "char: " << x << '\n'; }
void print(const char* s) { std::cout << "text: " << s << '\n'; }
int main() {
print(42);
print(3.14);
print('A');
print("hello");
}
Output:
int: 42
double: 3.14
char: A
text: hello
Each call matches one version exactly: 42 is an int, 3.14 a double, 'A' a char, and a string literal like "hello" becomes a const char*. You already rely on this idea every day: std::cout << works for ints, doubles and strings because operator<< is overloaded for all of them.
Three Ways to Overload
1. Different Number of Parameters
#include <iostream>
#include <cmath>
double area(double side) { // square
return side * side;
}
double area(double length, double width) { // rectangle
return length * width;
}
double area(double a, double b, double c) { // triangle (Heron's formula)
double s = (a + b + c) / 2;
return std::sqrt(s * (s - a) * (s - b) * (s - c));
}
int main() {
std::cout << "square : " << area(4.0) << '\n';
std::cout << "rectangle : " << area(4.0, 2.5) << '\n';
std::cout << "triangle : " << area(3.0, 4.0, 5.0) << '\n';
}
Output:
square : 16
rectangle : 10
triangle : 6
2. Different Types of Parameters
One overload can even call another, which avoids duplicating logic:
#include <iostream>
int largest(int a, int b) {
return (a > b) ? a : b;
}
int largest(int a, int b, int c) {
return largest(largest(a, b), c); // reuse the 2-argument version
}
double largest(double a, double b) {
return (a > b) ? a : b;
}
int main() {
std::cout << largest(3, 9) << '\n';
std::cout << largest(3, 9, 6) << '\n';
std::cout << largest(2.5, 1.75) << '\n';
}
Output:
9
9
2.5
3. Different Order of Parameter Types
#include <iostream>
void show(int roll, double cgpa) {
std::cout << "roll " << roll << ", cgpa " << cgpa << '\n';
}
void show(double cgpa, int roll) {
std::cout << "cgpa " << cgpa << ", roll " << roll << '\n';
}
int main() {
show(17, 8.6);
show(9.1, 23);
}
Output:
roll 17, cgpa 8.6
cgpa 9.1, roll 23
This is legal but risky: show(1, 2) (two ints) fits both equally badly, and the compiler refuses it as ambiguous (see below). Overloading only on parameter order is rarely a good idea in real code.
What Does NOT Count as a Different Overload
The compiler identifies a function by its signature: the name plus the list of parameter types (for member functions, also their const/reference qualifiers, which you will meet with classes). Some differences are not part of the signature:
Attempt | Allowed as overload? | Why |
|---|---|---|
Different return type only: | No | Return type is not part of the signature; a call |
Top-level | No | The caller's value is copied either way, so the |
A type alias: | No | An alias is just another name for the same type |
Different parameter names only: | No | Names are not part of the type |
| Yes | Different types (though calls can become ambiguous) |
The errors g++ gives:
int getValue() { return 10; }
double getValue() { return 10.5; }
error: ambiguating new declaration of 'double getValue()'
void g(int x) {}
void g(const int x) {}
error: redefinition of 'void g(int)'
Notice how g++ reports the second one as g(int): it has already dropped the top-level const. You may still declare void g(int x); and define void g(const int x) { ... }; they are the same function, and the const just stops the body from changing its own copy.
Overloads must differ in the number, types or order of parameters. Return type alone is never enough.
How the Compiler Chooses: Overload Resolution
When you call an overloaded name, the compiler runs overload resolution in three steps:
Collect candidates: all visible functions with that name.
Keep the viable ones: the right number of parameters, and each argument can be converted to the parameter type somehow.
Pick the best: rank each argument's conversion. The winner must be at least as good as every other viable function for every argument, and strictly better for at least one. If no single function wins, the call is ambiguous and does not compile.
The ranks, from best to worst:
Rank | What it includes | Examples |
|---|---|---|
1. Exact match | Same type, or trivial adjustments (array → pointer, adding |
|
2. Promotion | Integral promotion of small types to |
|
3. Standard conversion | All other built-in conversions |
|
4. User-defined conversion | Through a constructor or conversion operator of a class |
|
5. Ellipsis | Matching a C-style |
|
Promotions Win Over Conversions
#include <iostream>
void f(int) { std::cout << "f(int)\n"; }
void f(double) { std::cout << "f(double)\n"; }
int main() {
short s = 5;
float x = 2.5f;
f(10); // exact match
f(2.5); // exact match
f('A'); // char -> int : integral promotion
f(s); // short -> int : integral promotion
f(x); // float -> double : floating-point promotion
f(true); // bool -> int : integral promotion
}
Output:
f(int)
f(double)
f(int)
f(int)
f(double)
f(int)
Take f('A'). Converting char → int is a promotion (rank 2); char → double is a conversion (rank 3). Promotion is better, so f(int) wins. Same story for float, which promotes to double.
Ambiguous Calls
Trouble starts when two candidates need conversions of the same rank. Adding a long to the program above:
void f(int) {}
void f(double) {}
int main() {
long n = 5;
f(n);
}
error: call of overloaded 'f(long int&)' is ambiguous
note: candidate 1: 'void f(int)'
note: candidate 2: 'void f(double)'
long → int and long → double are both standard conversions (rank 3). Neither is better, so the compiler gives up rather than guess. (The & in long int& is just g++'s way of saying the argument is an lvalue, i.e. a named variable.)
A classic GATE/interview trap is overloading on float and double:
void h(float) {}
void h(double) {}
int main() {
h(5);
}
error: call of overloaded 'h(int)' is ambiguous
note: candidate 1: 'void h(float)'
note: candidate 2: 'void h(double)'
Many students expect h(double), because "double is the default floating type". But int → double is a conversion, not a promotion; only float → double is a promotion. Both candidates are rank 3, so it is ambiguous. h(5.0) picks h(double) and h(5.0f) picks h(float), both exact matches.
With several arguments, a function must be at least as good for every argument:
void show(int, double) {}
void show(double, int) {}
int main() {
show(1, 2);
}
error: call of overloaded 'show(int, int)' is ambiguous
The first overload is better for argument 1, the second for argument 2. No overall winner, so the call is ambiguous.
The bool vs std::string Surprise
#include <iostream>
#include <string>
void describe(bool b) { std::cout << "bool: " << b << '\n'; }
void describe(std::string s) { std::cout << "string: " << s << '\n'; }
int main() {
describe("hello"); // surprise!
describe(std::string("hello")); // what we wanted
using namespace std::string_literals;
describe("hello"s); // C++14 string literal
}
Output:
bool: 1
string: hello
string: hello
Why does describe("hello") call the bool version? The literal decays to const char*. Converting a pointer to bool is a built-in standard conversion (rank 3), while making a std::string from it needs a constructor, which is a user-defined conversion (rank 4). Rank 3 wins. Pass a real std::string, or use the C++14 s suffix, to get the intended overload.
Overloading and Scope: Inner Names Hide Outer Ones
Overloads only compete if they are in the same scope. A declaration of the same name in an inner scope hides all outer versions; it does not add to them.
#include <iostream>
void report(int x) { std::cout << "report(int) " << x << '\n'; }
void report(double x) { std::cout << "report(double) " << x << '\n'; }
int main() {
report(2.5); // report(double)
{
void report(int); // block-scope declaration hides BOTH outer ones
report(2.5); // only report(int) is visible: 2.5 -> 2
}
}
Output:
report(double) 2.5
report(int) 2
Name lookup stops at the first scope where the name is found, and overload resolution only considers what lookup found. Block-scope function declarations are rare in practice, but the very same rule causes a famous surprise with classes: a function in a derived class hides all base-class overloads of that name (you will see this in Inheritance).
How Overloading Works Underneath: Name Mangling
The linker, which joins compiled files into one program, needs every function to have a unique name. So the C++ compiler mangles each name by encoding the parameter types into it. Compiling these definitions with g++ and listing the symbols with nm:
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
long add(long a, long b, long c) { return a + b + c; }
extern "C" int legacy_sum(int a, int b) { return a + b; }
_Z3adddd → add(double, double)
_Z3addii → add(int, int)
_Z3addlll → add(long, long, long)
legacy_sum → not mangled
Read _Z3addii as: _Z (mangled name), 3add (a 3-letter name "add"), ii (two int parameters). This is the Itanium C++ ABI scheme used by g++ and Clang; MSVC uses a different scheme. The return type is not encoded for ordinary functions, which is another way of seeing why it cannot distinguish overloads.
extern "C" turns mangling off, so that C code (which knows nothing about overloading) can call the function. The price: at most one function with a given name may have C linkage, so two extern "C" functions can never be overloads of each other (C has no way to tell them apart).
When Should You Overload?
Yes: when the functions do the same conceptual job on different inputs:
area(...),print(...),largest(...).No: when they do different jobs.
process(int)that saves to a file andprocess(double)that sends an email will confuse every reader.If many overloads have identical bodies differing only in type, a template (see Templates) is usually the better tool.
If overloads differ only by "with or without the last argument", default arguments may be simpler; that is the next chapter.
Common Mistakes
Trying to overload on return type only.
Overloading on
int/longorfloat/doubleand then calling with a literal of a third type, causing ambiguity.Assuming
int→doubleis a promotion. It is a conversion; onlyfloat→doubleis a floating-point promotion.Forgetting that a
const char*argument prefersbooloverstd::string.Declaring a function with the same name in an inner scope and expecting the outer overloads to still be considered.
Interview and GATE Questions
Q1. Can two functions differ only in their return type?
No. Overloads must differ in their parameter lists. The return type is not part of a (non-template) function's signature, so int f(); and double f(); in the same scope is a compile error.
Q2. Given void f(int); and void f(double);, which is called by f('x'), f(2.5f) and f(10L)?
void f(int); and void f(double);, which is called by f('x'), f(2.5f) and f(10L)?f('x') → f(int) (integral promotion). f(2.5f) → f(double) (floating-point promotion). f(10L) → compile error, ambiguous: long → int and long → double are both standard conversions.
Q3. Are void g(int) and void g(const int) valid overloads?
void g(int) and void g(const int) valid overloads?No. Top-level const on a parameter passed by value is ignored when forming the function type, so they declare the same function. Defining both gives "redefinition of 'void g(int)'". (By contrast, const on what a pointer or reference refers to, as in g(int&) vs g(const int&), does create different overloads.)
Q4. Is function overloading compile-time or run-time polymorphism?
Compile-time (static) polymorphism. The compiler selects the overload from the static types of the arguments, and the call is bound before the program runs. Virtual functions provide run-time polymorphism.
Q5. What is name mangling and why does C++ need it?
Name mangling is the compiler encoding a function's parameter types (and namespace/class) into its symbol name, e.g. _Z3addii for add(int, int) under the Itanium ABI. It lets overloaded functions with the same source name have distinct names at link time. extern "C" disables it for compatibility with C, which is why two extern "C" functions cannot share a name.
Q6. Why does describe("hi") call describe(bool) instead of describe(std::string)?
describe("hi") call describe(bool) instead of describe(std::string)?The literal decays to const char*. Pointer → bool is a standard conversion, while const char* → std::string is a user-defined conversion (via a constructor). Standard conversions rank higher, so the bool overload wins.
Summary
Overloading: same name, same scope, different parameter lists (number, types or order).
Return type, parameter names, type aliases and top-level
conston by-value parameters do not create new overloads.The compiler chooses at compile time via overload resolution: exact match > promotion > standard conversion > user-defined conversion > ellipsis.
If no candidate is strictly best, the call is ambiguous and fails to compile.
Only
float→doubleand small integers →intare promotions;int→doubleis a conversion.Overloads in an inner scope hide outer ones. Name mangling makes overloads distinct for the linker;
extern "C"turns it off.
Overload when the job is the same and only the inputs differ, and keep the overload set small enough that every call has one obvious winner.