1 / 41

Object Oriented Programming Dr. Alon Schclar

Object Oriented Programming Dr. Alon Schclar. Based on slides by Elhanan Borenstein (now at Stanford http://www.stanford.edu/~ebo/). Agenda. Administration Course Overview Introduction to OOP and C++ Function Overloading & Default Parameters Arguments By Reference cin / cout

malory
Télécharger la présentation

Object Oriented Programming Dr. Alon Schclar

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Object OrientedProgrammingDr. Alon Schclar Based on slides by Elhanan Borenstein (now at Stanford http://www.stanford.edu/~ebo/)

  2. Agenda • Administration • Course Overview • Introduction to OOP and C++ • Function Overloading & Default Parameters • Arguments By Reference • cin / cout • Inline Functions • Memory Allocation • Additional Improvements

  3. Administration Course Page • Web: http://www2.mta.ac.il/~amirk/cpp/2010 • Exercises • Presentation & Example from class • E-Mail: alon.schclar@gmail.com • Reception hour: Tuesday 14-15 (prior email please) • Where: Weston 332 Books • Object Oriented Programming and C++ / Amir Kirsh • The C++ Programming Language / Bjarne Stroustrup • Effective C++, More Effective C++ / Scott Meyers

  4. Course Overview • OOP vs. C++ (can write any C++ app in c) Knowledge of C is required!!! Syllabus (partial !!!) • Introduction to OOP • C++ • Overloading functions & operators • Classes & Objects • Inheritance & Polymorphism • … • Templates & STL • Introduction to OOD

  5. Introduction to OOP and C++ Why OOP? • “Software Crisis” in procedural programming: • Too many modules… • Too many functions… An expensive mess!!! • Too many variables… • Better organization of the code • Smaller code • Reuse of code • In C – function pointers – not elegant • Easier design, analysis and implementation • Easier and more efficient scalability

  6. Introduction to OOP and C++ The Solution - Classes • The natural solution: focus on data!!! • instead of focusing on operations - functions • Define the data entities we want to use… • Each entity is implemented as a class and defines: • The data we want to store. • The operations that could be applied to this data. • Example: • College administration • Students – details, registration, tuition • Courses • Registration to courses

  7. Introduction to OOP and C++ The Solution - Classes • Classes • Objects – are instances of class • Like structs (~classes) and variable of type struct (~objects) • Still need a procedural application to create and use the objects • However – can create wrap in a managing class

  8. Introduction to OOP and C++ C++ • An Object-Oriented extension of C. • Any C program is also valid in C++ • Backward compatibility • Still contains non-OOP characteristics • global variables and functions • As before – everything starts at main • Still using pointers !!!! • Java and C# do not have pointers - references, garbage collection • Contains many cosmetic improvements • ‘//’ for one line comments

  9. Introduction to OOP and C++ C++ main OO elements • Encapsulation • data and functionality under the same roof - class • Inheritance • Define a new class based on an existing one • Polymorphism • Powerful mechanism for reusability • Template (example: swap) (C++ only) • Powerful mechanism for reusability – same code for different types • Can be done in C using the precompiler • Exceptions (C++ only)

  10. Chapter 3Before Classes…

  11. Function Overloading Motivation and Usage • Avoid writing / knowing / using a huge number of functions which in effect, do the same action. How? • Define numerous functions with the same name • Different interface (prototypes) - arguments • as long as the compiler can distinguish according to its arguments which function should be used. void printNice(int i);void printNice(int i, char ch);void printNice(int i, char* str);void printNice(float f);

  12. Function Overloading Example from booklet • void doSomething (int t) ; • void doSomething(int t, char ch); • void doSomething (int t, char* string) ; • void doSomething (float t) ; • void main ( ) • { • doSomething (13); // calls line 1 function • doSomething (2.5f) ; // calls line 4 function • doSomething (3, ‘A’) ; // calls line 2 function • doSomething (4.5f, "H") ; // calls line 3 function! • // Auto casting on 1st argument • doSomething(3, 4.5f); // calls line 2 function • / / Auto casting on 2nd argument • }

  13. Function Overloading The Ambiguity Problem • When the compiler cannot positively determine which function should be used, it will announce an ambiguity error. • Ambiguity problem – who’s fault is it? • The calling not the definition (unless two similar functions) void printNice(double d);void printNice(float f); printNice(3); // which function is invoked ?

  14. Function Overloading Example from booklet • void LetsHaveFun (float f) ; • void LetsHaveFun (double d) ; • void main ( ) • { • LetsHaveFun (3.5f) ; // Fine - goes to line 1 function • LetsHaveFun(3.12) ; // Fine - goes to line 2 function • LetsHaveFun( (float)3) ; // goes to line 1 function • LetsHaveFun( (double)3); // goes to line 2 function • LetsHaveFun(3); // Error - ambiquity • // Compiler can't decide what casting to perform ... • // int to floatorint to double • // (there aren't any rules for this) • }

  15. Function Overloading The Ambiguity Problem • Can we solve an ambiguity problem according to the return value? Why? • It is not mandatory to assign the returned value to a variable of the same type // These two function can't live together.. . int Coffee (int type) ; // returns coffee price char* Coffee(int type); // returns coffee type as string void main() { printf ("%d", Coffee (2) ) ; } Already a problem

  16. Default Parameters Usage • It is possible to define default values for the last arguments of a function. • These arguments can then be dropped when calling the functions. • It is still possible to give a different value when calling the function (all previous arguments must be specified too). • Arguments order – first (frequent non-default), last - rest • Default values are defined in the function prototype !!! (use a comment notation in the implementation…) • Compiler fills the missing values void printReallyNice(char* str, int fontSize = 10, char color = 0);

  17. Default Parameters Example from booklet • Message(char* Message, int x=1, int y=1, int color=1); • void main() • { • Message("Ma Shlornhem haiom?"); • Message ("Ifm fine", 10, 10); • Message("Ma Shlom Shlomo?", 20, 20, BLUE); • } • Message (char* Message, int x, int y, int color) • { • // Implementation of function Message • }

  18. Default Parameters Beware of ambiguity – from booklet // Default before required parameters - can't go int BuildArr(int num=10, int* arr); // Correct way: int BuildArr (int* arr, int num=10) ; // function WhichMovie - old and new version int WhichMovie(int Cinema, int HallNurn); int WhichMovie(int Cinema, int HallNum=1, int City=1); // Can't survive both // Correct way: keep the boldface line

  19. By Reference (ByRef) Arguments Argument in C • In C, arguments are passed by Value. Changing the value of the arguments in the function, does not change the value of the original variables. • If we wish to change the value of the original arguments, we can use pointers. Examples on page 27 Argument in C++ • In C++, arguments are still passed by Value, but… • A function can ask to get an argument by reference (ByRef). • Internally implemented with pointers • Hidden from the user – a safer and more elegant

  20. ByRef Arguments Example from booklet - BAD 1. void swap (int, int) ; 2. 3. void main() 4. { 5. int a, b; 6. printf("a=%d b=%dW, a, b) ; 7. swap(a,b) ; 8. printf("a=%d b=%d" , a, b) ; 9. } 10. 11. void swap(int A, int B) 12. { 13. int temp=A; 14. A=B; 15. B=temp; 16. }

  21. ByRef Arguments Example from booklet – C style – works but not C++ 1. void swap(int* A, int* B) 2. { 3. int temp=*A; 4. *A=*B; 5 . *B=temp; 6. } 7. 8. void main ( ) 9. { 10. int a, b; 11. ... 12. // send the address of a and b ! ! ! 13.swap(&a,&b); 14. ... 15. }

  22. ByRef Arguments Example from booklet – Finally C++ 1. void swap(int& A, int& B) 2. { 3. int temp=A; 4. A=B; 5 . B=temp; 6. } 7. 8. void main ( ) 9. { 10. int a, b; 11. ... 12. // send a nd b – not by address (pointers) – by Ref 13.swap(a, b); 14. ... 15. }

  23. By Reference (ByRef) Return Values • A function can return a value by reference. • In effect returns a location in memory • A by reference return value must be alive after the function terminates (global, input variables, …). • Beware of dangling refs (refs to local variables0 • Can be used as LValue in assignment • Example: Find() • Returns a ref to a searched array cell • Page 29 • What will happen if find=6 ?

  24. Ref LValues Example from booklet – • #include <iostream.h> • #include <stdio.h> • #include <conio.h> • void PrintArr(int* arr, int size) • { • for(int i=0; i<size; i++) • { • printf("%d, ", arr[i]); • } • printf("\n"); • }

  25. int& GetOut(int* arr, int size, int& LookFor) { for(int i=0; i<size; i++) { if(arr[i]==LookFor) return arr[i]; } return LookFor; }

  26. void main() { int Arr[]={1,4,2,5,3}; int size=sizeof(Arr)/sizeof(Arr[0]); PrintArr(Arr, size); int find=5; GetOut(Arr, size, find)=13; PrintArr(Arr, size); getch(); }

  27. By Reference (ByRef) variables • Like a synonym • Mainly used for inheritance polymorphism 1. int i=3; 2. int j=5; 3. // Reference variable must be initialized in declaration 4. // int &k; - Error – no initialization 5. int &k=i; 6. k=31; // means - i=31 7. k=j; // means - i = j 8. j=12; // doesn't change i or k 9. i=8; // k becomes 8 10. printf("i=%d, k=%d”, i, k); // prints : i=8, k=8

  28. Input & Output (cin, cout) I/O in C • When using printf (or scanf), the programmer must define the type of each argument. • We could write a different function for each type • Not elegant – many similar names I/O in C++ • We can use the I/O objects cin and cout • (defined in <iostream.h>) can be further overloaded • We will use the operators “<<“ and “>>” (like +) • Thanks to function overloading, there is no need to define the type of the arguments.

  29. Input & Output (cin, cout) Example 1 (output) #include <iostream.h>void main( ){ int i = 23; char *str = “hello”; cout<<str; cout<<i<<endl; cout<<“the value of i is “<<i<<endl; cout<<(char)65;}

  30. I/O Example from booklet – • 1. #include<iostream.h> • 3. void main() • 4. { • 5. int i=5; • char* string="This is great \n”; • cout <<string; • cout<<i<<endl; // endl - means end-of-line = “\n” • 9. // The compiler doesn't get confused, I • 10. // even i f we pull one over on it: • 11. cout<<"This is int:"<<4.5; • 12. // And we can tell a whole story in one line ! • 13. cout<<"i="<<i<<"r string="<<string<<endl; • 14. cout<<'A’; // prints the character A • 15. cout<<65; // prints the number 65 • 16. cout<<(char)65; // prints the character A • 17. }

  31. Input & Output (cin, cout) Example 2 (input) #include <iostream.h>void main( ){ int age; char str[100]; cout<<“Please enter your name”; cin>>str; cout<<“Please enter your age”; cin>>age;} No pointers – how ?

  32. I/O Example from booklet – 1. #include<iostream. h> 3. void main ( ) 4. { 5. int i; 6. char string [40] ; 7. char ch; 8. 9. cout<<"Please be kind enough to type a string:"; 10. cin >> string ; 11. // The next word - till a white space - will enter into 12. // the char array named string . 13. // Same as: scanf("%s”, string ) ; 14. 15. cout<<"Now please be friendly and give me int: "; 16. cin>>i; 17. // The next word - will be converted to int and entered 18. // into i. Same as: scanf("%d”, &i); 19. 20. cout<<"Now please be helpful and provide one char: "; 21. cin>>ch; 22. // The first char entered will go into ch. 23. // Same as: scanf("%c”,& ch); 24. }

  33. Inline Functions Motivation • Each function call requires allocating memory on the stack. • Overhead may outweighs the benefits (especially in small functions that will be called many times). • Macros have other problems: • No type checking on the arguments • Readability • Side effect i++

  34. Inline Functions The solution • Inline functions. • The functions are embedded within the call - replicated • The compiler is not bound by the inline declaration. • In case too long, missing return etc. -> no inline for you • In debug – must specify – otherwise it is a warning • Must implement in the file where used • or include in .h file • Bigger exe – the same as macros

  35. Inline Functions Examples from booklet – 1. #define ROUND (num) (int) ( (num) + 0.5) 2. 3. inline int round(double num) 4. { 5. return (int) (num+0.5); 6. } 1. #define SQUARE (num) (num) * (num) 2. 3. inline double square(double num) 4. { 5. return (num*num); 6. }

  36. Memory Allocation Allocation • Memory allocation is implemented with the command “new”. • No casting, sizeof is required (unlike C). • For arrays allocation we will use “new[n]”. Freeing • To free allocated memory, we will use the command “delete”. • For arrays, we will use “delete[ ]”.

  37. Memory allocation Example from booklet – 1. char* string; 2. string=new char[20]; 3. cout<<"Please insert string: "; 4. cin>>string; 5. 6. int* pInt=new int; 7. cout<<"Please insert int: "; 8. cin>>*pInt; 9. 10. int n; 11. cout<<"What is the size of the array? "; 12. cin>>n; 13. float* FloatArr=new float[n]; 14. ... 15. 16. delete [ ]string; 17. delete pInt; 18. delete [ ]FloatArr;

  38. 13. // depends on the options marked in the compiler ! ! !) 14. for (int i=0; i<temp; i++) 15. { 16. // item is declared again and again 17. // for every entry in the loop 18. int item=GetItem (i) *13; 19. ImportantVar+=item; 20. } 21. // The following line may be allowed, depending 22. // on the options marked in the compiler ... 23. cout<<i; 24. ... 25. }

  39. Additional Improvements Comments • C++ still supports the conventional notation of comments from C: /* this is a comment */ • In addition, we can use a single comment line starting with // // initialization int index; // this is also a comment

  40. Additional Improvements Variable Definition • Variables can be defined at any point in the code. • Should be used wisely!!!! 1. void main() 2 . { 3 . int ImportantVar; // controls for the nuclear explosion 4. ... 5. cout<<"Haide Sara"; 6. ... 7. // We define here the variable temp to hold the outcome 8. // of the function 'GoGetItf 9. int temp=GoGetIt ("Hu-Ha") ; 10. 11. // The loop index i is declared here inside the for ! 12. // (The question whether i is available after the loo;,

  41. Additional Improvements Structs and enums Definition • When defining a struct or enum variable, no need to declare it is a struct / enum. • Reminder: in C we usually used typedef for this problem 1. struct Student 2. { 3. char* StudentName; 4. int MoneyResources; 5. // etc. 6. }; 7. 8. void main ( ) 9. { 10. Student Dudu; / / in C: struct Student Dudu 11. }

More Related