6.6 — Same name, different inputs (overloading)

📘 Chapter 6⏱ about 1 min read✍️ Beginner friendly
Read one box at a time. No rush.

Function overloading#

Two functions can share a name if their parameters are different. C++ picks the right one based on what you pass in.

C++▶ Run
int largest(int a, int b){    return (a > b) ? a : b;} double largest(double a, double b){    return (a > b) ? a : b;} int main(){    std::cout << largest(3, 9) << '\n';      // uses the int version    std::cout << largest(2.5, 1.5) << '\n';  // uses the double version    return 0;}
Conditional operator (? :)

condition ? a : b is a tiny if/else that gives a value: "if condition, then a, otherwise b". It is called the conditional operator.

What counts as different?#

  • A different number of parameters, or
  • Different types of parameters.

A different return type alone is not enough.

Tip

Instead of writing the same function for every type, you can write it once with a template. See 11.1 — Templates: code for any type.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.