C++ Functions

Function Overloading

C++
#include <iostream>
using namespace std;

int area(int s)              { return s * s; }
int area(int l, int b)       { return l * b; }
double area(double r)        { return 3.14159 * r * r; }

int main() {
    cout << area(4) << " " << area(3, 5) << " " << area(1.0) << endl;
    return 0;
}
16 15 3.14159

Default Arguments

C++
double interest(double p, double rate = 7.5, int years = 1) {
    return p * rate * years / 100;
}
// interest(1000) = 75, interest(1000, 8) = 80, interest(1000, 8, 2) = 160

Inline Functions

inline asks the compiler to replace the call with the function body, saving call overhead for tiny functions. It's a hint; the compiler may ignore it.

C++
inline int square(int x) { return x * x; }
Track your progress through the C++ course