C++ Function Overloading
▪ In C++, two functions can have the same name if the
number and/or type of arguments passed is different.
▪ These functions having the same name but different
arguments are known as overloaded functions.
What is For example:
Function ▪ Here, all 4 functions are overloaded functions.
Overloading?
▪ Notice that the return types of all these 4 functions
are not the same.
▪ Overloaded functions may or may not have different
return types but they must have different arguments.
For example,
Here, both functions have the same name, the same
type, and the same number of arguments.
Hence, the compiler will throw an error.
Overloading Using
Different Types of
Parameter
Overloading Using Different Number of Parameters
Output
▪ Here, the display() function is called three times
with different arguments.
▪ Depending on the number and type of arguments
passed, the corresponding display() function is
called.
▪ The return type of all these functions is the same
but that need not be the case for function
overloading.
Write two overloaded functions named calculateSquare.
One function should take an integer as input and return its
square (integer).
Exercises 01 The other function should take a double as input and
return its square (double).
Write a main function to demonstrate the usage of both
functions.
Write three overloaded functions named print_info.
The first function takes a string (name).
The second function takes a string (name) and an integer
(age).
Exercise 02 The third function takes a string (name), an integer (age),
and a string (city).
Write a main function to call each print_info function with
appropriate arguments.
#include <iostream>
// Overloaded function to calculate the square of an integer
int calculateSquare(int num) {
return num * num;}
// Overloaded function to calculate the square of a double
double calculateSquare(double num) {
return num * num;}
int main() {
int intNum = 5;
double doubleNum = 3.14;
// Call the integer version of calculateSquare
int intSquare = calculateSquare(intNum);
std::cout << "The square of " << intNum << " is: " << intSquare << std::endl;
// Call the double version of calculateSquare
double doubleSquare = calculateSquare(doubleNum);
std::cout << "The square of " << doubleNum << " is: " << doubleSquare << std::endl;
return 0;}
Create a simple class named Calculator with a member
function named add.
Overload the add function to take:
Exercise 03 o Two integers.
o Three integers.
Create an object of the Calculator class in the main
function and call both versions of the add function.
Thank You!