Skip to Content
Navigating C++ and Object-Oriented Design
book

Navigating C++ and Object-Oriented Design

by Paul Anderson, Gail Anderson
October 1997
Intermediate to advanced
800 pages
20h 48m
English
Pearson
Content preview from Navigating C++ and Object-Oriented Design

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Exploring C++20: The Programmer's Introduction to C++

Exploring C++20: The Programmer's Introduction to C++

Ray Lischner

Publisher Resources

ISBN: 0135327482Purchase book