Function Overloading

Multiple functions with same name

Interview Relevant: Polymorphism concept

Function Overloading

C++ allows multiple functions with the same name but different parameters.

Overloading Rules

  • Functions must differ in parameter types or count
  • Return type alone cannot distinguish functions
  • Compiler selects best match at compile time
  • Part of compile-time polymorphism

Code Examples

Function overloading with different parameter types.

cpp
1// Overloaded print functions
2void print(int x) {
3    cout << "Integer: " << x << endl;
4}
5
6void print(double x) {
7    cout << "Double: " << x << endl;
8}
9
10void print(const string& x) {
11    cout << "String: " << x << endl;
12}
13
14// Compiler selects based on arguments
15print(42);        // Calls print(int)
16print(3.14);      // Calls print(double)
17print("hello");   // Calls print(const string&)

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In