Codiqo

Learn C++ · lesson 23 of 61 · about 8 minutes

Defaults and Overloading

Frame the exit sign with lines: give a parameter a default value, and write two functions with the same name for different arguments.

What you'll learn

  • Add default arguments
  • Overload a function by parameter types
  • Predict which overload is called

A sign at the exit

At the exit, the adventure shows a sign with the hero's name, a line of = above it and a line of - below it, each exactly as long as the sign. One function, line(int length, char symbol = '='), makes a line of any length, and = is used unless another symbol is given. A second function with the same name, line(const std::string& text), measures the text and calls the first one.

Default arguments

double tip(double bill, double percent = 10) uses 10 when the caller leaves percent out. Defaults go at the end of the parameter list.

A default tip

#include <iostream>

double tip(double bill, double percent = 10) {
    return bill * percent / 100;
}

int main() {
    std::cout << tip(50) << " " << tip(50, 20) << "\n";
}

Output

5 10

Overloading

Several functions can share a name if their parameter types differ. The compiler picks the one that matches the arguments.

One name, three versions

#include <iostream>
#include <string>

std::string describe(int n) { return "int " + std::to_string(n); }
std::string describe(double d) { return "double " + std::to_string(d); }
std::string describe(const std::string& s) { return "text " + s; }

int main() {
    std::cout << describe(3) << "\n";
    std::cout << describe(2.5) << "\n";
    std::cout << describe(std::string("hi")) << "\n";
}

Output

int 3
double 2.500000
text hi

Both lines for a short sign

#include <iostream>
#include <string>

// a line of any length, made of = unless another symbol is given
std::string line(int length, char symbol = '=') {
    return std::string(length, symbol);
}

// a line exactly as long as some text
std::string line(const std::string& text) {
    return line(text.size());
}

int main() {
    std::string exitSign = "Bo reaches the exit!";
    std::cout << line(exitSign) << "\n";
    std::cout << exitSign << "\n";
    std::cout << line(exitSign.size(), '-') << "\n";
    std::cout << line(4) << line(4, '~') << "\n";
}

Output

====================
Bo reaches the exit!
--------------------
====~~~~

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.