cs31 lecture 17

Type implementations x cons error prone type

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: d returned by the function the x Remember: C arrays are always passed-by-reference 89 Function overloading x What to do when two prototypes for a same functionality What are desired? (ex: divide, for both floats and ints)
 are x Solution 1: use distinct function names int divint(int x, int y)
; float divfloat(float x, float y)
; x Solution 2: use function overloading (C++ ok, not in C)
 int div(int x, int y)
; float div(float x, float y)
; 90 Overloading rules x Two functions can have the same name in C++ if their Two signature differs by more than the return type signature x Signature: the “base type” of the function Compute it by eliminating all qualifiers (const, etc.)
 Usually noted foo : typeArg1 x typeArg2 x … -> returnType Example: int div(int x, int y)
; // signature is div: int x int -> int int div(const int x, const int y)
; // signature is div: int x int -> int float div(float x, double y)
; // signature is div: float x double -> int 91 Pros and cons x Pros: Provide a single function name for a single functionality Very modular: implement a functionality with a default type, and Very when the library gets extended with a new type simply create implementations for this type implementations x Cons: Error-prone: type promotion 92 Finding the right implementation 1. There is an exact signature match between the signature of the call There and the signature of the function definition. and 2. There is a signature...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online