cs31 lecture 8

Main int bar 42 int foobar bar bar foobar 14 more

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: e observations x The concept of pointer (in C, C++) differs slightly from the The concept of reference concept x In C++, you must pass explicitly a variable as an argument In of a function which is pass-by-reference of E.g., foo(0, 1, 2) is forbidden in the previous example x In C (and C++), you can pass a numerical address as an In argument of a function which is of pointer type argument 15 Examples 16 More on references x A reference to a variable can be declared within a function It is a standard type qualifier x Be careful: when a function terminates, the (temporary) Be memory slots allocated to it are “destroyed” memory x A reference can be passed as argument, and returned by the function the x Remember: arrays are always passed-by-reference 17 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); 18 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 19 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 20 Finding the right implementation 1. There is an exact signature match between the signature of the call Ther...
View Full Document

This note was uploaded on 04/03/2014 for the course CS 31 taught by Professor Melkanoff during the Fall '00 term at UCLA.

Ask a homework question - tutors are online