In this tutorial, we aim to delve deep into the concepts of function overloading and inline functions in C++. These are fundamental aspects of C++ that can significantly enhance the efficiency and readability of your code when utilized correctly.
You will learn what function overloading and inline functions are, when and how to use them, and the benefits they offer in programming.
Basic knowledge of C++ programming is required. Familiarity with functions in C++ would be an advantage.
Function overloading is a feature in C++ where two or more functions can have the same name but different parameters. It allows you to use the same function name to perform different tasks.
void print(int i) {
std::cout << "Printing int: " << i << std::endl;
}
void print(double f) {
std::cout << "Printing float: " << f << std::endl;
}
void print(char* c) {
std::cout << "Printing character: " << c << std::endl;
}
An inline function is a function in C++ which is expanded in line when it is called. When the inline function is called whole code of the inline function gets inserted or substituted at the point of inline function call.
inline void hello() {
std::cout << "Hello, World!" << std::endl;
}
#include <iostream>
// Function to add two integer numbers
int add(int a, int b) {
return a + b;
}
// Overloaded function to add three integer numbers
int add(int a, int b, int c) {
return a + b + c;
}
int main() {
std::cout << add(10, 20) << std::endl; // Calls the first function
std::cout << add(10, 20, 30) << std::endl; // Calls the overloaded function
return 0;
}
Expected Output:
30
60
#include <iostream>
inline int Max(int x, int y) {
return (x > y)? x : y;
}
int main() {
std::cout << "Max (20,10): " << Max(20,10) << std::endl;
return 0;
}
Expected Output:
Max (20,10): 20
In this tutorial, we covered the concepts of function overloading and inline functions in C++. Function overloading allows multiple functions to share the same name but perform different tasks based on their parameters. Inline functions, on the other hand, are a way to increase the execution time of a program by reducing function call overhead.
#include <iostream>
int multiply(int a, int b) {
return a * b;
}
double multiply(double a, double b) {
return a * b;
}
double multiply(int a, double b) {
return a * b;
}
int main() {
std::cout << multiply(10, 20) << std::endl;
std::cout << multiply(10.5, 20.5) << std::endl;
std::cout << multiply(10, 20.5) << std::endl;
return 0;
}
Expected Output:
200
215.25
205
#include <iostream>
inline int Square(int x) {
return x * x;
}
int main() {
std::cout << "Square of 10: " << Square(10) << std::endl;
return 0;
}
Expected Output:
Square of 10: 100