Function overloading in C++

Level 3135 keystrokes

Defines two functions named square, one for int and one for double. The compiler picks the one that matches the argument type: square(5) prints 25 and square(2.5) prints 6.25.

C++ code

// Version for int arguments
1int square(int x) {
2 return x * x;
3}
4
// Same name, different parameter type: this is overloading
5double square(double x) {
6 return x * x;
7}
8
// 5 is an int, so the int version runs: 25
9cout << square(5) << endl;
// 2.5 is a double, so the double version runs: 6.25
10cout << square(2.5) << endl;

Output

25
6.25
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 8
  • ;× 4
  • (× 4
  • )× 4
  • {× 2
  • }× 2
  • *× 2
  • .× 1

More C++ examples at level 3

← C++ typing practice