C++ Function Overloading: Rules, Ambiguity Resolution & Name Mangling

Function Overloading is a feature of C++ where two or more functions can share the exact same name, provided their parameter lists (number, types, or order of arguments) are distinctly different. This is a primary form of Compile-Time (Static) Polymorphism.

Example: Overloaded Math Functions

#include <iostream>
#include <string>

int add(int a, int b) {
    return a + b;
}

double add(double a, double b) {
    return a + b;
}

std::string add(const std::string& a, const std::string& b) {
    return a + b;
}

int main() {
    std::cout << "Integers: " << add(10, 20) << "\n";                 // Calls add(int, int) -> 30
    std::cout << "Doubles:  " << add(4.5, 2.5) << "\n";               // Calls add(double, double) -> 7.0
    std::cout << "Strings:  " << add("Hello ", "Veewom") << "\n";     // Calls add(string, string) -> Hello Veewom
    return 0;
}
BCA Ambiguity Warning:

Beware of default arguments and type promotions! If you define void print(int x) and void print(float x), calling print(5.5) causes ambiguity because 5.5 is a double literal, which can convert equally to int or float. Write print(5.5f) to be explicit.

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. Can you overload a function in C++ by return type alone?

No! Functions CANNOT be overloaded based on return type alone (e.g. int func() and double func() cannot coexist). The compiler selects an overload based solely on the number, types, and sequence of its parameter arguments.

Q2. What is Name Mangling in C++?

Name mangling is the compiler mechanism that generates unique internal linker symbol names for overloaded functions by encoding their parameter types into the symbol name (e.g. add(int, int) becomes _Z3addii in GCC).

Explore Related C++ Tutorials & Next Steps

Boost your C++ proficiency by studying these closely connected core modules:

C++ Functions

Fundamentals of parameter passing.

Function Templates

Generic functions vs overloaded functions.

C++ Polymorphism

Comparing compile-time vs runtime polymorphism.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!