π Function overloading allows multiple functions with the same name but different parameters.
Function overloading in C++ is a feature that allows multiple functions to have the same name, as long as their parameter lists are different. This means that the functions must differ in the number of parameters, the types of parameters, or both.
#include <iostream>
using namespace std;
void greet() {
cout << "Hello!" << endl;
}
void greet(string name) {
cout << "Hello, " << name << "!" << endl;
}
void greet(string name, int age) {
cout << "Hello, " << name << ". You are " << age << " years old." << endl;
}
int main() {
greet();
greet("Ram");
greet("Sita", 20);
return 0;
}
π Default arguments are used when a parameter value is not passed during function call.
Default arguments in C++ allow you to specify default values for function parameters. If a caller omits an argument with a default value, the compiler automatically substitutes the default.
#include <iostream>
using namespace std;
void welcome(string name = "Guest") {
cout << "Welcome, " << name << "!" << endl;
}
int main() {
welcome(); // Uses default value
welcome("Bibek"); // Overrides default
return 0;
}
Write a program in C++ to calculate simple interest using function. Set the default value of interest rate as 10%.
π Inline functions are expanded in-line during compilation to save the function call overhead.
In C++, an inline function is a function that the compiler can replace with the function's code at the point of the function call. This process is called "inline expansion." The primary goal of using inline functions is to reduce the overhead associated with function calls, potentially improving performance, especially for small, frequently called functions.
<aside> π‘
One solution to this problem is to use macro definitions, popularly known as macros. Preprocessor macros are popular in C. The major drawback with macros is that they are not really functions and therefore, the usual error checking does not occur during compilation.
</aside>
To declare a function as inline, you use theΒ inline keyword before the function's return type.
#include <iostream>
using namespace std;
inline int square(int x) {
return x * x;
}
int main() {
cout << "Square of 4: " << square(4) << endl;
cout << "Square of 7: " << square(7) << endl;
return 0;
}
<aside> π‘
Inline functions are most suitable for: Small functions with simple logic, Functions that are called frequently, and Functions where performance is critical. However, it makes the program to take up more memory because the statements that define the inline function are reproduced at each point where the function is called. So, a trade-off becomes necessary.
</aside>