The Wayback Machine - https://web.archive.org/web/20241118224651/https://www.geeksforgeeks.org/function-overloading-vs-function-templates-in-cpp/
Open In App

Function Overloading vs Function Templates in C++

Last Updated : 26 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C++, both function overloading and function templates allow us to create functions that can operate on different types of data. While they might seem similar, they are used for different purposes. In this article, we will learn the differences between function overloading and function templates, and understand when to use each.

Function Overloading in C++

Function overloading in C++ allows us to define multiple functions with the same name but with different parameters. The compiler determines which function to call based on the arguments passed to it.

  • The functions must have different parameter lists (either in number or type of parameters).
  • The return type of the functions can be the same or different.
  • The compiler uses the argument types and number to decide which function to invoke.

The parameters should follow any one or more than one of the following conditions for Function overloading:

void functionName(int a);
void functionName(double a);
void functionName(int a, int b);

When to Use Function Overloading in C++?

Use function overloading when you need to perform similar operations on different types or numbers of inputs.

Example

The below example demonstrates how function overloading works in C++.

C++
// C++ program to demonstrate function overloading

#include <iostream>
using namespace std;

// Function to print an integer
void print(int i) { cout << "Integer: " << i << endl; }

// Function to print a double
void print(double f) { cout << "Double: " << f << endl; }

// Function to print a string
void print(string s) { cout << "String: " << s << endl; }

int main()
{
    // Call the print function with an integer argument
    print(10);

    // Call the print function with a double argument
    print(10.5);

    // Call the print function with a string argument
    print("Hello");

    return 0;
}

Output
Integer: 10
Double: 10.5
String: Hello

Time Complexity: O(1) for function call resolution.
Auxiliary Space: O(1)

Function Templates in C++

We use function templates to define a generic function template that can work with any data type. Instead of writing multiple overloaded functions, we simply write a single template function.

  • The template keyword is used to define a template.
  • T is a placeholder for the data type that will be specified when the function is called.
  • The compiler generates the appropriate function definition based on the type of arguments passed.

Syntax:

template <typename T>
void functionName(T a);

template <typename T>
T functionName(T a, T b);

When to Use Function Templates in C++?

Use function templates when you need a single function to work with different data types without rewriting the function for each type.

Example

C++
// C++ program to demonstrate template function usage

#include <iostream>
using namespace std;

// Template function to print values of any type
template <typename T> void print(T value)
{
    // Output the value of the specified type
    cout << "Value: " << value << endl;
}

int main()
{
    // Call the print function with an integer argument
    print(10);

    // Call the print function with a double argument
    print(10.5);

    // Call the print function with a string literal
    // argument
    print("Hello");

    return 0;
}

Output
Value: 10
Value: 10.5
Value: Hello

Time Complexity: O(1) for function template instantiation.
Auxiliary Space: O(1)

To know more about the topic refer to Generics in C++.

Difference Between Function Overloading and Function Templates in C++

The following table illustrates he key differences between function overloading and function templates:

Feature

Function Overloading

Function Templates

Purpose

Define multiple functions with the same name but different parameters

Define a single function to work with different data types

Syntax

void functionName(int a);<br>void functionName(double a);<br>void functionName(int a, int b);

template <typename T><br>void functionName(T a);<br>template <typename T><br>T functionName(T a, T b);

Code Duplication

Multiple functions, potentially similar code

Single function, no code duplication

Type Safety

Checked at compile-time

Checked at compile-time

Readability

Clear which function is called based on parameters

More abstract, but cleaner for multiple types

Flexibility

Limited to predefined function signatures

More flexible, works with any data type

Maintenance

Harder to maintain due to multiple functions

Easier to maintain, single function definition

Conclusion

Function overloading and function templates are both important features of C++ that allow for flexible and reusable code. We can use function overloading when we have similar functions that operate on different types or numbers of parameters and use function templates when we want a single function to work with different data types, reducing code duplication and increasing flexibility.


Previous Article
Next Article

Similar Reads

Overloading function templates in C++
Template: A template is a tool that reduces the efforts in writing the same code as templates can be used at those places.A template function can be overloaded either by a non-template function or using an ordinary function template. Function Overloading: In function overloading, the function may have the same definition, but with different argumen
3 min read
error: call of overloaded ‘function(x)’ is ambiguous | Ambiguity in Function overloading in C++
Pre-requisite: Function Overloading in C++ Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading. Two or more functions are said to be overloaded if they differ in any of th
9 min read
Function Overloading vs Function Overriding in C++
Function Overloading (achieved at compile time) Function Overloading provides multiple definitions of the function by changing signature i.e. changing number of parameters, change datatype of parameters, return type doesn’t play any role. It can be done in base as well as derived class.Example: void area(int a); void area(int a, int b); C/C++ Code
3 min read
Advantages and Disadvantages of Function Overloading in C++
Function overloading is one of the important features of object-oriented programming. It allows users to have more than one function having the same name but different properties. Overloaded functions enable users to supply different semantics for a function, depending on the signature of functions. Advantages of function overloading are as follows
3 min read
Overloading of function-call operator in C++
In this article, we will discuss the Overloading of the function-call operators in C++. The function call operator is denoted by “()” which is used to call function and pass parameters. It is overloaded by the instance of the class known as a function object.When the function call operator is overloaded, an operator function is created that can be
3 min read
Menu-Based program to find the volume of 3D shapes using function overloading
Given the dimensions of the 3D Shapes like Cube, Cuboid, or Cylinder, the task is to find the volume of all the 3D Shapes using function overloading. Examples: Input: Cube: L = 3, Cuboid: L = 3, B = 4, H = 3, Cylinder: R = 2, H = 7Output:Volume of Cube: 27Volume of Cuboid: 36Volume of Cylinder: 176 Input: Cube: L = 2, Cuboid: L = 3, B = 2, H = 3, C
4 min read
Function overloading and const keyword
Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading. In Function Overloading “Function” name should be the same and the arguments should be different. Function overloading
5 min read
Function Overloading and float in C++
Although polymorphism is a widely useful phenomena in C++ yet it can be quite complicated at times. For instance consider the following code snippet: C/C++ Code #include&lt;iostream&gt; using namespace std; void test(float s,float t) { cout &lt;&lt; &quot;Function with float called &quot;; } void test(int s, int t) { cout
2 min read
How to Use Default Arguments in Function Overloading in C++?
In C++, we can provide the default values for the input arguments into the functions and it is also supported in function overloading. In this article, we will learn how to use default arguments in function overloading in C++. Default Arguments in Function Overloading in C++We can define the default value in function overloading as we do it in the
2 min read
Function Overloading and Return Type in C++
Function overloading is possible in C++ and Java but only if the functions must differ from each other by the types and the number of arguments in the argument list. However, functions can not be overloaded if they differ only in the return type. Why is Function overloading not possible with different return types and identical parameters? Function
2 min read
Function Overloading in C++
Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading. In Function Overloading “Function” name should be the same and the arguments should be different. Function overloading
4 min read
not1 and not2 function templates in C++ STL with Examples
These are functions which takes unary and binary function object(functors) and returns complement of that function objects. It can be usable in competitive programming to get complement of binary and unary functions. These functions are very useful when writing code for complement function is harder or lengthy. For example, if we want to delete con
3 min read
Abbreviated Function Templates in C++ 20
Abbreviated Function Template is a new feature introduced in C++20 to simplify the syntax of function template definition. Traditionally, we use function templates to define a function that can take parameters of different types. But sometimes, it might get complicated and hard to understand. In these cases, we can implement an abbreviated function
3 min read
Variadic function templates in C++
Variadic templates are class or function templates, that can take any variable(zero or more) number of arguments. In C++, templates can have a fixed number of parameters only that have to be specified at the time of declaration. However, variadic templates help to overcome this issue. Douglas Gregor and Jaakko Järvi came up with this feature for C+
3 min read
Difference between Preprocessor Directives and Function Templates in C++
Preprocessor Directives are programs that process our source code before compilation. There are a number of steps involved between writing a program and executing a program in C / C++. Below is the program to illustrate the functionality of Function Templates: [GFGTABS] C++ // C++ program to illustrate // preprocessor directives #include <bits/s
3 min read
C++ | Operator Overloading | Question 10
Which of the following operator functions cannot be global, i.e., must be a member function. (A) new (B) delete (C) Conversion Operator (D) All of the above Answer: (C) Explanation: new and delete can be global, see following example. #include #include #include using namespace std; class Myclass { int x; public: friend void* operator new(size_t siz
1 min read
Namespaces in C++ | Set 4 (Overloading, and Exchange of Data in different Namespaces)
Prerequisite: Namespace in C++ | Set 1 (Introduction)Namespace in C++ | Set 2 (Extending namespace and Unnamed namespace)Namespace in C++ | Set 3 (Accessing, creating header, nesting and aliasing) In this article, we will discuss the concept of data sharing between different namespaces, how to access and Overload standard operators to work for user
5 min read
C++ Program to concatenate two strings using Operator Overloading
Pre-requisite: Operator Overloading in C++Given two strings. The task is to concatenate the two strings using Operator Overloading in C++. Example: Input: str1 = "hello", str2 = "world" Output: helloworld Input: str1 = "Geeks", str2 = "World" Output: GeeksWorld Approach 1: Using unary operator overloading. To concatenate two strings using unary ope
3 min read
Increment (++) and Decrement (--) Operator Overloading in C++
Operator overloading is a feature in object-oriented programming which allows a programmer to redefine a built-in operator to work with user-defined data types. Why Operator Overloading? Let's say we have defined a class Integer for handling operations on integers. We can have functions add(), subtract(), multiply() and divide() for handling the re
4 min read
C++ program to compare two Strings using Operator Overloading
Pre-requisite: Operator Overloading in C++Given two strings, how to check if the two strings are equal or not, using Operator Overloading. Examples: Input: ABCD, XYZ Output: ABCD is not equal to XYZ ABCD is greater than XYZ Input: Geeks, Geeks Output: Geeks is equal to Geeks Approach: Using binary operator overloading. Declare a class with a string
3 min read
Operator Overloading '<<' and '>>' operator in a linked list class
Prerequisite: Operator Overloading in C++, Linked List in C++ C++ comes with libraries that provide ways for performing Input and Output. In C++, Input and Output are performed as a sequence of bytes, also known as streams. Input and Output stream are managed by the iostream library. cin and cout are the standard objects for the input stream and ou
4 min read
Matrix operations using operator overloading
Pre-requisite: Operator OverloadingGiven two matrix mat1[][] and mat2[][] of NxN dimensions, the task is to perform Matrix Operations using Operator Overloading.Examples: Input: arr1[][] = { {1, 2, 3}, {4, 5, 6}, {1, 2, 3}}, arr2[][] = { {1, 2, 3}, {4, 5, 16}, {1, 2, 3}} Output: Addition of two given Matrices is: 2 4 6 8 10 22 2 4 6 Subtraction of
13 min read
Overloading the Comma Operator
In C++, we can overload the comma operator using Operator Overloading. For Example: For "Send the query X to the server Y and put the result in variable Z", the "and" plays the role of the comma. The comma operator (, ) is used to isolate two or more expressions that are included where only one expression is expected. When the set of expressions ha
5 min read
Add given timestamps by overloading + operator in C++ Time Class
In C++, we can make operators to work for user-defined classes. This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading.In this article, we will overload an operator ‘+’ in the Time class so that we can concatenate two timestamps by just using +. Example: Input: T
3 min read
Input/Output Operators Overloading in C++
Operator Overloading is a part of Polymorphism, which enables the feature because of which we can directly use operators with user-defined classes and objects. To read more about this, refer to the article operator overloading in C++. Input/Output Operators(>>/<<) Overloading in C++ We can't directly use the Input/Output Operators (>
2 min read
C++ Logical (&&, ||, !) Operator Overloading
Prerequisites: OperatorsOperator Overloading Logical operators are used for combining two or more conditions or constraints or to complement the evaluation of the original condition in consideration. The result returns a Boolean value, i.e., true or false. In C++, there are 3 logical operators: Logical AND (&&): This operator returns true o
3 min read
C++ Bitwise Operator Overloading
Prerequisites: Operator OverloadingBitwise Operator in C/C++ In C++, there are a total of six bitwise operators. The six bitwise operators are bitwise AND (&), bitwise OR (|), bitwise XOR (^), left shift (<<), right shift (>>), and bitwise NOT (~). The & (bitwise AND) in C++ takes two numbers as operands and does AND on every bi
7 min read
Count number of Unique Triangles using Operator overloading
Given N triangles along with the length of their three sides as a, b and c. The task is to count the number of unique triangles out of these N given triangles. Two triangles are different from one another if they have at least one of the sides different. Examples: Input: arr[] = {{3, 1, 2}, {2, 1, 4}, {4, 5, 6}, {6, 5, 4}, {4, 5, 6}, {5, 4, 6}}; Ou
10 min read
Typecast Operator Overloading in C++
In C++, the typecast operator can be overloaded to customize the behavior of casting operators to define how user-defined data types can be converted into other types. This enables developers to define how instances of a class are converted to other types, providing more control over implicit type conversions. By overloading typecast operators, dev
6 min read
Overloading stream insertion (<>) operators in C++
In C++, stream insertion operator "<<" is used for output and extraction operator ">>" is used for input. We must know the following things before we start overloading these operators. 1) cout is an object of ostream class and cin is an object of istream class 2) These operators must be overloaded as a global function. And if we want to
2 min read
Practice Tags :
three90RightbarBannerImg