C++

Function Overloading with Examples in C++

905
0
Function Overloading with Examples in C++

Function overloading is a feature of C++ that allows functions to have the same name but with different parameters or argument lists. This enables programmers to use the same function name for different tasks, making code more readable and maintainable. Here are some examples of function overloading in C++:

Example 1: Calculating the area of a square and rectangle

#include <iostream>
using namespace std;

int area(int side) {
    return side * side; // area of a square
}

int area(int length, int width) {
    return length * width; // area of a rectangle
}

int main() {
    int s = 5;
    int l = 10, w = 5;

    cout << "Area of square: " << area(s) << endl;
    cout << "Area of rectangle: " << area(l, w) << endl;

    return 0;
}
C++

In this example, we have defined two functions named area() with different parameters. One function calculates the area of a square, taking only one argument, while the other function calculates the area of a rectangle, taking two arguments. We can call each function separately to calculate the area of a square and rectangle.

Example 2: Concatenating strings

#include <iostream>
#include <string>
using namespace std;

string concatenate(string str1, string str2) {
    return str1 + str2;
}

string concatenate(string str1, string str2, string str3) {
    return str1 + str2 + str3;
}

int main() {
    string s1 = "Hello ";
    string s2 = "world!";
    string s3 = " How are you?";

    cout << concatenate(s1, s2) << endl;
    cout << concatenate(s1, s2, s3) << endl;

    return 0;
}
C++

In this example, we have defined two functions named concatenate() with different parameters. One function concatenates two strings, while the other function concatenates three strings. We can call each function separately to concatenate two or three strings.

Example 3: Finding the maximum of two or three numbers

#include <iostream>
using namespace std;

int maximum(int a, int b) {
    return (a > b) ? a : b;
}

int maximum(int a, int b, int c) {
    int max = (a > b) ? a : b;
    return (max > c) ? max : c;
}

int main() {
    int x = 5, y = 10, z = 15;

    cout << "Max of two numbers: " << maximum(x, y) << endl;
    cout << "Max of three numbers: " << maximum(x, y, z) << endl;

    return 0;
}
C++

In this example, we have defined two functions named maximum() with different parameters. One function finds the maximum of two numbers, while the other function finds the maximum of three numbers. We can call each function separately to find the maximum of two or three numbers.

xalgord
WRITTEN BY

xalgord

Constantly learning & adapting to new technologies. Passionate about solving complex problems with code. #programming #softwareengineering

Leave a Reply