SyntaxStudy
Sign Up
C++ Functions, Overloading, and Default Arguments
C++ Beginner 1 min read

Functions, Overloading, and Default Arguments

C++ supports function overloading, allowing multiple functions to share the same name as long as their parameter lists differ. The compiler selects the correct overload at compile time based on the types and number of arguments provided. Overloading enables expressive APIs where a single conceptual operation — such as 'print' — can handle diverse input types without forcing the caller to use different names. Default argument values can be specified in a function declaration, allowing callers to omit trailing arguments. Defaults must be declared from right to left and defined only once — typically in the header. This feature reduces boilerplate in call sites while keeping functions flexible. Inline functions suggest to the compiler that the function body should be expanded at the call site rather than generating a traditional call. Modern compilers make inlining decisions automatically, but the 'inline' keyword is still meaningful for header-defined functions in multiple translation units, where it suppresses the 'multiple definition' linker error.
Example
#include <iostream>
#include <string>

// Overloaded print functions
void print(int value) {
    std::cout << "int: " << value << "\n";
}

void print(double value) {
    std::cout << "double: " << value << "\n";
}

void print(const std::string& value) {
    std::cout << "string: " << value << "\n";
}

// Default arguments — defaults only in declaration
void connect(const std::string& host,
             int port = 443,
             bool secure = true) {
    std::cout << (secure ? "https" : "http")
              << "://" << host << ":" << port << "\n";
}

// Inline helper
inline int square(int n) { return n * n; }

int main() {
    print(42);
    print(3.14);
    print(std::string("overload"));

    connect("example.com");              // uses defaults
    connect("example.com", 8080);        // overrides port
    connect("example.com", 80, false);   // overrides both

    std::cout << "square(7) = " << square(7) << "\n";

    return 0;
}