C++ Functions

C++ functions are reusable blocks of code with a name, parameters and a return type. C++ adds powerful features over C, such as overloading, default arguments and references.

Defining a Function

#include <iostream>

int square(int x) {
    return x * x;
}

int main() {
    std::cout << square(9) << '\n';
}
81

Default Arguments

Parameters can have default values used when the caller leaves them out. Defaults must come at the end of the list.

#include <iostream>
#include <string>

void greet(const std::string& name, const std::string& greeting = "Hello") {
    std::cout << greeting << ", " << name << "!\n";
}

int main() {
    greet("Ali");
    greet("Ali", "Salaam");
}
Hello, Ali!
Salaam, Ali!

Function Overloading

Several functions can share a name if their parameter types differ. The compiler picks the best match.

#include <iostream>
#include <string>

void show(int v)                { std::cout << "int: " << v << '\n'; }
void show(double v)             { std::cout << "double: " << v << '\n'; }
void show(const std::string& v) { std::cout << "string: " << v << '\n'; }

int main() {
    show(5);
    show(2.5);
    show(std::string{"hi"});
}
int: 5
double: 2.5
string: hi

Pass by Value vs Pass by Reference

Pass by value copies the argument. Pass by reference (with &) lets the function use the original. Use const& for large objects you only read.

#include <iostream>

void addBonusCopy(int score) { score += 10; }
void addBonusRef(int& score) { score += 10; }

int main() {
    int s = 50;
    addBonusCopy(s);
    std::cout << s << '\n';
    addBonusRef(s);
    std::cout << s << '\n';
}
50
60

Function Guidelines

  • Keep functions short and focused on one task.
  • Pass small types (int, double) by value.
  • Pass large types (string, vector) by const reference.
  • Return values instead of using output parameters when possible.

Frequently asked questions

What is function overloading in C++?

It means defining multiple functions with the same name but different parameter lists. The compiler chooses which to call based on the argument types.

When should I pass by const reference?

Pass objects that are expensive to copy, like std::string or std::vector, by const reference when the function only needs to read them.

Can a C++ function return multiple values?

Yes, return a std::pair, std::tuple or a struct, and unpack it with structured bindings: auto [a, b] = f();