Course outline · 0% complete

0/27 lessons0%

Course overview →

Overloading and Default Arguments

lesson 4-3 · ~9 min · 11/27

Overloading exists because inventing a new name for every parameter type scales badly. C, which lacks it, needs abs, labs, fabs, and fabsf for one idea — absolute value. C++ lets one name serve them all and picks the right body from the argument types at compile time; the standard library leans on this everywhere (std::to_string alone has nine overloads).

Same name, different parameters

C++ lets several functions share a name as long as their parameter lists differ. This is overloading, and the compiler picks the right one from the argument types at the call site:

int    twice(int x)    { return x * 2; }
double twice(double x) { return x * 2.0; }
std::string twice(const std::string& s) { return s + s; }

twice(4);       // calls the int version, 8
twice(1.5);     // calls the double version, 3.0
twice(std::string("ab"));  // "abab"

Python cannot do this (a second def twice replaces the first). Note that the return type alone is not enough to overload: two functions differing only in return type will not compile.

Default arguments

void repeat(std::string s, int times = 2) { ... }

repeat("hi");      // times is 2
repeat("hi", 5);   // times is 5

Defaults must be the trailing parameters, same as Python.

Code exercise · cpp

Run this and match each call to the overload it selects.

Quiz

Why can't these two coexist? `int parse(std::string s)` and `double parse(std::string s)`

Code exercise · cpp

Your turn. Write two overloads of `area`: `area(double side)` for a square and `area(double w, double h)` for a rectangle. The program should print `25` then `12`.