Presentation is loading. Please wait.

Presentation is loading. Please wait.

OOP Spring 2007 – Recitation 21 Object Oriented Programming Spring 2007 Recitation 2.

Similar presentations


Presentation on theme: "OOP Spring 2007 – Recitation 21 Object Oriented Programming Spring 2007 Recitation 2."— Presentation transcript:

1 OOP Spring 2007 – Recitation 21 Object Oriented Programming Spring 2007 Recitation 2

2 OOP Spring 2007 – Recitation 22 Today: Function overloading Default arguments Constructor/destructor References Copy constructors

3 OOP Spring 2007 – Recitation 23 Function Overloading

4 OOP Spring 2007 – Recitation 24 Overloading In C++ it’s possible to define several functions with the same name, but different parameter list: 1) int pow(int b, int p); 2) double pow(double b, double p); 3) Complex pow(Complex b, Complex p); The call pow(1,2) will call function (1), while pow( Complex(2.4,7.8), Complex(1,1) ) will call function (3). The resolution is made at compile-time.

5 OOP Spring 2007 – Recitation 25 Call Resolution The functions must differ in their parameter list. The return type does not matter. When the compiler needs to resolve a call to an overloaded function, it: 1.Finds best match for each argument separately according to a set of rules; 2.Calls the function that is the best match for one argument and better than or equal match for all other arguments.

6 OOP Spring 2007 – Recitation 26 Ambiguities If there are two equally good ways to make a conversion, the compiler will refuse to choose. It will result in compile-time error (“Ambiguous conversion”), but only when the conversion is required: void f(int);// No problem void f(char);// No problem f(3.14);// Ambiguous call

7 OOP Spring 2007 – Recitation 27 Default Arguments Values The Way to Type Less

8 OOP Spring 2007 – Recitation 28 Why? Imagine you have to use a function that has 3 arguments. bool is_leap(int year, int base, char calndr); 99% of the time the year is base 10 and the calendar is Gregorian. Calling is_leap() each time with 3 arguments is tedious. What if is_leap() knew default values for base and calendar ?

9 OOP Spring 2007 – Recitation 29 How? In C++ we can specify default values: bool is_leap (int year, int base = 10, char calndr = 'G'); And now is_leap(1983); is_leap(1983, 10); is_leap(1983, 10, 'G');  are all the same. You can specify default values for all or part of function’s arguments.

10 OOP Spring 2007 – Recitation 210 Restrictions Once you give a default value to an argument, you have to give a default value to all arguments that follow: bool is_leap(int year, int base=10, char calndr); is an error.

11 OOP Spring 2007 – Recitation 211 More Restrictions A default value is valid only within its file. Thus we will usually specify default values in function declarations in header files. A default value cannot be overridden. Thus don’t try to specify default value if a function declaration already has one (for example, if you include a header with default value for an argument).

12 OOP Spring 2007 – Recitation 212 Constructors & Destructors

13 OOP Spring 2007 – Recitation 213 Con/De-struction When object “comes to life”, as well as when it “dies”, some actions must be taken. constructor destructorWhen object is created, the class constructor is called. When object dies, the class destructor is called. Constructor for class Car is defined by Car(parameter list). Multiple constructors are possible, differing by the parameters. Destructor is defined by ~Car().

14 OOP Spring 2007 – Recitation 214 C’tor - example Class FloatPoint { int numer; int denom; Public: FloatPoint(); FloatPoint(int n); FloatPoint(int n,int d); };

15 OOP Spring 2007 – Recitation 215 C’tor - example FloatPoint::FloatPoint(){ numer = 0; denom = 1; } FloatPoint::FloatPoint(int n){ numer = n; denom = 1; } FloatPoint::FloatPoint(int n,int d){ numer = n; denom = d; }

16 OOP Spring 2007 – Recitation 216 C’tor - example int main() { FloatPoint f1(3,5); FloatPoint f2; floatPoint f3(2); FloatPoint f4(f2); FloatPoint f5(); … } ?

17 OOP Spring 2007 – Recitation 217 C’tor - example We could have used only one constructor with default arguments: FloatPoint(int n=0, int d=1);

18 OOP Spring 2007 – Recitation 218 C’tor Static Arrays FloatPoint a[3] = { FloatPoint(3,5), FloatPoint(2), FloatPoint() }; Dynamic Arrays FloatPoint *pa; pa = new FloatPoint[3]; Without default c’tor or c’tor with no parameters – Error!

19 OOP Spring 2007 – Recitation 219 D’tor - example Class String { char* str; Public: String(char *s =“”); ~String(); };

20 OOP Spring 2007 – Recitation 220 D’tor - example String::String(char *s =“”){ str = new char[strlen(s)+1]; strcpy(str,s); } String::~String(){ delete[]str; }

21 OOP Spring 2007 – Recitation 221 D’tor - example int main() { String book(“Harry Potter”); String *hero = new String(“Harry”); delete hero; return 0; }

22 OOP Spring 2007 – Recitation 222 References The Way Around Pointers

23 OOP Spring 2007 – Recitation 223 Why? C++ inherits C’s way of by-value parameter passing. Two problems: –If you need to change the parameter inside the function, you need to pass a pointer to it. –If you need to pass a large object, it’s better to use pointer to avoid the cost of copying. The function and its caller need to use pointer syntax.

24 OOP Spring 2007 – Recitation 224 A swap() With Pointers void SwapWithPointers(int *v1, int *v2) { int tmp = *v2; *v2 = *v1; *v1 = tmp; } SwapWithPointers(&i, &j);

25 OOP Spring 2007 – Recitation 225 A Reference A reference is just another name for existing variable. To define a reference, use & after the type. int &a is a reference to an int, called a. The reference must be initialized when it is created. int &a = j; initializes a to be another name for j.

26 OOP Spring 2007 – Recitation 226 What Is It Exactly? After the reference is initialized, it cannot be changed to “refer” to another variable. The initialization is not assignment, we tell the compiler that a is another name for j. After the initialization we can use a wherever we can use j. They are different names for the same value.

27 OOP Spring 2007 – Recitation 227 How It Looks int i= 10;// Define variable named i int &a= i;// Define another name for i int b= i;// Define variable named b // with the value of i i = 5;// i==5, a==5, b==10 a = 20;// i==20, a==20, b==10 b = 0;// i==20, a==20, b==0

28 OOP Spring 2007 – Recitation 228 Reference Parameters We can also tell the compiler that a function parameter is “another name” for a variable passed to it, i.e. a reference. Then we can change the parameter inside the function and the variable passed to it will also change. No copying around large objects – references are like pointers.

29 OOP Spring 2007 – Recitation 229 A swap() With References void SwapWithReferences(int &v1, int &v2) { int tmp = v2; v2 = v1; v1 = tmp; } SwapWithReferences(i, j);

30 OOP Spring 2007 – Recitation 230 Relation to Pointers A reference is like a pointer BUT –A reference cannot be changed to “point” to another place. –No need for special syntax. –A reference ALWAYS needs to “point” somewhere. There is no NULL reference. Side note: it’s possible to define references to pointers.

31 OOP Spring 2007 – Recitation 231 const Use What if we don’t want to copy large object, but also don’t want to allow changing it? Use const reference: void func(const string& s); means that s is a reference for the variable passed to func(), but it cannot be changed inside func().

32 OOP Spring 2007 – Recitation 232 Copy Constructor

33 OOP Spring 2007 – Recitation 233 Copy Constructor A constructor for class A with single parameter of type const A& is called copy constructor. It is used when a parameter of type class A is passed by value (to copy the argument into the function) or when a parameter of type class A is returned by value.

34 OOP Spring 2007 – Recitation 234 inline Functions The Way to Efficiency

35 OOP Spring 2007 – Recitation 235 Why Not #define? We want to write short and simple function In C you were told you can write macros for short functions: #define max(a, b) ((a) > (b) ? (a) : (b)) Macros are bad: –Need to parenthesize all arguments: #define square(x) x*x square(1+1) –Strange things happen: int a=5, b=0; max(++a, b); max(++a, b+10);

36 OOP Spring 2007 – Recitation 236 Functions Are Better, But… Function call costs CPU time (copy arguments, create local variables, “tell” the processor to jump to another place). Inline functions are a compromise – it’s a way to tell a compiler to replace function call with its body. Simply add inline before function declaration or definition.

37 OOP Spring 2007 – Recitation 237 Works, But Not Always The inline keyword is a hint to the compiler to replace function call with its body: –If a function is too long, it won’t do it. –If a function is recursive, it won’t do it. –There are other cases, when inline won’t differ. In general, we’ll use inline if a function is two-three lines long (max(), min(), get(), set(), etc.)

38 OOP Spring 2007 – Recitation 238 Important Note Since inline function calls should be replaced with function’s body when we compile our code, the compiler must see the code for that function too. The way to do it – place inline functions in header files (.h, not.cpp, as we do with regular functions).

39 OOP Spring 2007 – Recitation 239 The New max() inline int max(int a, int b) { return a > b ? a : b; } cout << max(5, 15) << '\n';

40 OOP Spring 2007 – Recitation 240 Another Way of Inlining If the body of a class method is defined in the class body, the method is implicitly inline: class Widget { public: string name() { return _name; } private: string _name; }; Here name() is inline, even though we didn’t write it.

41 OOP Spring 2007 – Recitation 241 Use Inlining Judiciously Inlining is a wonderful idea, BUT –Increases program size (code bloat). –Complicates debugging. –Requires clients to recompile (and not relink) if code changes. –Compilers add a lot of code into constructors and destructors, thus inlining them is a bad idea.


Download ppt "OOP Spring 2007 – Recitation 21 Object Oriented Programming Spring 2007 Recitation 2."

Similar presentations


Ads by Google