Defining Overloaded Functions
Consider a database application with several functions to find a record based on name, phone number, account number, and so on. Function overloading lets us define a collection of functions, each named lookup
, that differ in terms of how they do the search. We can call lookup
passing a value of any of several types:
Record lookup(const Account&); // find by AccountRecord lookup(const Phone&); // find by PhoneRecord lookup(const Name&); // find by NameAccount acct;Phone phone;Record r1 = lookup(acct); // call version that takes an AccountRecord r2 = lookup(phone); // call version that takes a Phone
Here, all three functions share the same name, yet they are three distinct functions. The compiler uses the ...
Get C++ Primer, Fifth Edition 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.