Curriculum / C++ / Lesson 08

Functions in C++

C++ functions work like C's, but add two powerful features: default arguments (a parameter can have a fallback value) and function overloading (multiple functions can share a name if their parameter lists differ)..

8 of 10
beginner 📖 5 min read 🎯 1 question

Functions

C++ functions work like C's, but add two powerful features: default arguments (a parameter can have a fallback value) and function overloading (multiple functions can share a name if their parameter lists differ).

💡 Key insight Function overloading lets add(int,int) and add(double,double) coexist — the compiler picks the right one based on the arguments.

Syntax

syntax
returnType functionName(type param = defaultValue) {
    return value;
}

Example

Both functions are named add; the compiler chooses which one to call based on the argument types.

cpp
#include <iostream>
using namespace std;

int add(int a, int b) {
    return a + b;
}

double add(double a, double b) {
    return a + b;
}

int main() {
    cout << add(2, 3) << endl;
    cout << add(2.5, 3.5) << endl;
    return 0;
}
output5 6

Try it yourself

Copy this example into the C++ compiler and run it — try changing a value and see what happens.

Quick Quiz

1. What must differ between two overloaded functions with the same name?

Back to curriculum