9.1. Why Should Functions Be Generic?

Let's examine the following function, which determines a maximum from its two integer arguments.

inline int max(int a, int b) { 
   return a > b ? a : b;
}

int m = 43, n = 56;
cout << max(m, n) << endl;          // displays 56 (CORRECT)

double x = 4.3, y = 5.6;
cout << max(x, y) << endl;          // displays 5 (WRONG)

The first call to max() works, but the second one does not. Calls to max() with integer arguments match its signature exactly, but double arguments truncate fractional parts because of conversion rules (your compiler may report warnings here). The first cout statement displays the correct maximum (56), but the second cout statement does not.

We could overload max() with double arguments, but the code to determine ...

Get Navigating C++ and Object-Oriented Design now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.