← C++ from Scratch
Lesson 30 of 62 · 10 XP
Function overloading
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
In C++ you can have several functions with the same name if their parameters differ (in number or types). The compiler picks the right one by the arguments:
int area(int side) { return side * side; } // a square
int area(int w, int h) { return w * h; } // a rectangle
double area(double r) { return 3.14159 * r * r; } // a circle
area(4); // 16 — the first one
area(2, 5); // 10 — the second one
area(1.0); // 3.14… — the third one
They can't differ only in the type of the result: from the call f(1) it's impossible to tell which one to pick.
Task. Write two describe functions: describe(int) prints int: <number>,
describe(const std::string&) prints string: <string> (<length>). Read n, then n tokens:
if a token consists only of digits, call the int version (std::stoi); otherwise, the string one.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.