Function Overloading
Part of the Object Oriented Programming section of Coddy's C++ journey — lesson 57 of 104.
Function overloading allows you to define multiple functions with the same name but different parameter lists. The compiler selects the correct version based on the arguments you pass. This is a key form of compile-time polymorphism.
For overloading to work, functions must differ in their signature - the number of parameters, their types, or both:
class Calculator {
public:
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
};
Calculator calc;
calc.add(5, 3); // Calls add(int, int)
calc.add(2.5, 3.7); // Calls add(double, double)
calc.add(1, 2, 3); // Calls add(int, int, int)The compiler examines each call and matches it to the appropriate overload. This happens entirely at compile time, so there's no runtime overhead.
Important: Return type alone does not distinguish overloaded functions. The following would cause a compiler error:
int getValue();
double getValue(); // Error: cannot overload by return type onlyFunction overloading makes your code more intuitive. Instead of creating separate names like addInts, addDoubles, and addThreeInts, you use a single meaningful name and let the compiler handle the rest.
Challenge
EasyLet's build a message formatter class that demonstrates the power of function overloading. You'll create a Formatter class with multiple format() methods that handle different types of input, letting the compiler choose the right version based on what you pass in.
You'll organize your code across two files:
Formatter.h: Define aFormatterclass with overloadedformat()methods that handle different scenarios:- A method that takes a single
std::stringand prints:Message: <text> - A method that takes a
std::stringand anintpriority level, printing:[Priority <priority>] <text> - A method that takes a
std::stringand adoubletimestamp, printing:[<timestamp>s] <text> - A method that takes three
std::stringparameters (sender, receiver, message) and prints:From <sender> to <receiver>: <message>
format()— the compiler will select the correct one based on the arguments.- A method that takes a single
main.cpp: Read four inputs (each on a separate line):- A simple message text
- A priority level (integer)
- A timestamp (double)
- A sender name
Create a
Formatterobject and demonstrate all four overloaded methods:- Call
format()with just the message text - Call
format()with the message text and priority - Call
format()with the message text and timestamp - Call
format()with the sender, "Admin" as the receiver, and the message text
For example, with inputs System ready, 3, 12.5, and Server:
Message: System ready
[Priority 3] System ready
[12.5s] System ready
From Server to Admin: System readyNotice how you call the same method name format() four times, but each call invokes a different version based on the argument types and count. This is compile-time polymorphism in action — the compiler determines which overload to use before the program even runs.
Cheat sheet
Function overloading allows you to define multiple functions with the same name but different parameter lists. The compiler selects the correct version based on the arguments passed at compile time.
Functions must differ in their signature - the number of parameters, their types, or both:
class Calculator {
public:
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
};
Calculator calc;
calc.add(5, 3); // Calls add(int, int)
calc.add(2.5, 3.7); // Calls add(double, double)
calc.add(1, 2, 3); // Calls add(int, int, int)Important: Return type alone cannot distinguish overloaded functions:
int getValue();
double getValue(); // Error: cannot overload by return type onlyFunction overloading is a form of compile-time polymorphism with no runtime overhead.
Try it yourself
#include <iostream>
#include <string>
#include "Formatter.h"
using namespace std;
int main() {
// Read inputs
string message;
getline(cin, message);
int priority;
cin >> priority;
double timestamp;
cin >> timestamp;
cin.ignore();
string sender;
getline(cin, sender);
// TODO: Create a Formatter object
// TODO: Call format() with just the message text
// TODO: Call format() with message text and priority
// TODO: Call format() with message text and timestamp
// TODO: Call format() with sender, "Admin" as receiver, and message text
return 0;
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesC++ Build & CompilationHeader Files & Source FilesNamespaces & ScopeIntroduction to OOP in C++Classes vs ObjectsThe 'this' PointerMethods (Member Functions)Attributes (Data Members)Ctors & Dtors BasicsRecap - Simple Calculator4Class Properties
Instance vs Static MembersGetters and SettersConst Member FunctionsMutable KeywordStatic Methods and VariablesFriend Functions & ClassesRecap - Bank Account Manager7Inheritance
Basic InheritanceInheritance Access LevelsCtor & Dtor Call OrderMethod OverridingVirtual Functions & VTableMultiple InheritanceVirtual InheritanceRecap - Employee Hierarchy2Memory Management
Stack vs Heap MemoryPointers and ReferencesDynamic Memory (new/delete)Smart Pointers in C++RAII in C++Recap - Dynamic Array Manager5Encapsulation
Access Specifiers in C++Access Specifiers In DepthInformation HidingStruct vs ClassNested & Inner ClassesRecap - Student Records System8Polymorphism
Compile vs Runtime PolymorphFunction OverloadingVirtual Functions RevisitedPure Virtual FunctionsAbstract ClassesInterface Design in C++Dynamic Casting & RTTIRecap - Shape Calculator3Constructors & Destructors
Default ConstructorParameterized ConstructorCopy ConstructorMove ConstructorConstructor Init ListsDelegating ConstructorsDestructor Deep DiveRule of Three / Five / ZeroRecap - String Class6Operator Overloading
Intro to Operator OverloadArithmetic Operator OverloadComparison Operator OverloadStream OperatorsAssignment Operator Overload[] and () Operator OverloadType Conversion OperatorsRecap - Matrix Class9Templates
Function TemplatesClass TemplatesTemplate SpecializationVariadic TemplatesSFINAE & Type Traits BasicsRecap - Generic Container