C++C++ · Lesson 4 of 9

Functions & References

C++ functions add default arguments, function overloading, and references — things C wishes it had.

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

// Default arguments
string greet(const string& name, const string& title = "friend") {
    return "Hello, " + title + " " + name + "!";
}

// Function overloading — same name, different parameter types
double area(double radius) {
    return 3.14159 * radius * radius;
}

double area(double width, double height) {
    return width * height;
}

// Pass by reference — modifies the original
void increment(int& n) {
    n++;
}

// Pass by const reference — read-only, no copy
void printVec(const vector<int>& v) {
    for (int n : v) cout << n << " ";
    cout << "
";
}

// Template function — works with any comparable type
template<typename T>
T maxOf(T a, T b) {
    return a > b ? a : b;
}

int main() {
    cout << greet("Alice") << "
";           // Hello, friend Alice!
    cout << greet("Smith", "Dr.") << "
";    // Hello, Dr. Smith!

    cout << area(5.0) << "
";       // circle: 78.5398
    cout << area(4.0, 6.0) << "
";  // rect: 24

    int x = 10;
    increment(x);
    cout << x << "
";  // 11

    vector<int> nums = {1, 2, 3, 4, 5};
    printVec(nums);

    cout << maxOf(3, 7) << "
";          // 7 (int)
    cout << maxOf(3.14, 2.71) << "
";    // 3.14 (double)
    cout << maxOf(string("a"), string("z")) << "
";  // z (string)

    return 0;
}
◆ Note
Pass large objects (like vector or string) by const reference — const vector<int>&. This avoids copying the entire object. Pass small types (int, double, char) by value — copying them is cheap.