object oriented programming dr. alon schclar based on slides by elhanan borenstein (now at stanford...
TRANSCRIPT
Object OrientedProgramming
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 Inline Functions Memory Allocation Additional Improvements
Administration
Web: http://www2.mta.ac.il/~amirk/cpp/2010 Exercises Presentation & Example from class
E-Mail: [email protected] Reception hour: Tuesday 14-15 (prior email please) Where: Weston 332
Course Page
Object Oriented Programming and C++ / Amir Kirsh The C++ Programming Language / Bjarne Stroustrup Effective C++, More Effective C++ / Scott Meyers
Books
Course Overview
Introduction to OOP C++
Overloading functions & operators Classes & Objects Inheritance & Polymorphism …
Templates & STL Introduction to OOD
Syllabus (partial !!!)
OOP vs. C++ (can write any C++ app in c)
Knowledge of C is required!!!
Introduction to OOP and C++
“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
Why OOP?
Introduction to OOP and C++
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
The Solution - Classes
Introduction to OOP and C++
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
The Solution - Classes
Introduction to OOP and 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
C++
Introduction to OOP and C++
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)
C++ main OO elements
Chapter 3Before Classes…
Function Overloading
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);
Motivation and Usage
Function Overloading
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 functiondoSomething (2.5f) ; // calls line 4 functiondoSomething (3, ‘A’) ; // calls line 2 functiondoSomething (4.5f, "H") ; // calls line 3 function!// Auto casting on 1st argumentdoSomething(3, 4.5f); // calls line 2 function/ / Auto casting on 2nd argument
}
Example from booklet
Function Overloading
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);
The Ambiguity Problem
printNice(3); // which function is invoked ?
Function Overloading
void LetsHaveFun (float f) ;void LetsHaveFun (double d) ;
void main ( ){
LetsHaveFun (3.5f) ; // Fine - goes to line 1 functionLetsHaveFun(3.12) ; // Fine - goes to line 2 functionLetsHaveFun( (float)3) ; // goes to line 1 functionLetsHaveFun( (double)3); // goes to line 2 functionLetsHaveFun(3); // Error - ambiquity// Compiler can't decide what casting to perform ...// int to float or int to double// (there aren't any rules for this)
}
Example from booklet
Function Overloading
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
The Ambiguity Problem
// These two function can't live together.. .int Coffee (int type) ; // returns coffee pricechar* Coffee(int type); // returns coffee type as string
void main(){
printf ("%d", Coffee (2) ) ;}
Already a problem
Default Parameters
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);
Usage
Default Parameters
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}
Example from booklet
Default ParametersBeware of ambiguity – from booklet
// Default before required parameters - can't goint BuildArr(int num=10, int* arr);// Correct way:int BuildArr (int* arr, int num=10) ;
// function WhichMovie - old and new versionint 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
By Reference (ByRef) Arguments
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.
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
Argument in C++ Examples on page 27
ByRef Arguments
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. }
Example from booklet - BAD
ByRef Arguments
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. }
Example from booklet – C style – works but not C++
ByRef Arguments
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 Ref13. swap(a, b);14. ...15. }
Example from booklet – Finally C++
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 ?
Ref LValues
#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"); }
Example from booklet –
int& GetOut(int* arr, int size, int& LookFor){
for(int i=0; i<size; i++) {
if(arr[i]==LookFor)return arr[i];
}return LookFor;
}
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();}
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 declaration4. // int &k; - Error – no initialization5. int &k=i;6. k=31; // means - i=317. k=j; // means - i = j8. j=12; // doesn't change i or k9. i=8; // k becomes 810. printf("i=%d, k=%d”, i, k) ; // prints : i=8, k=8
Input & Output (cin, cout)
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.
I/O in C++
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;
}
I/O1. #include<iostream.h>3. void main()4. {5. int i=5;6. char* string="This is great \n”;7. cout <<string; 8. cout<<i<<endl; // endl - means end-of-line = “\n”9. // The compiler doesn't get confused, I10. // 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 A15. cout<<65; // prints the number 6516. cout<<(char)65; // prints the character A17. }
Example from booklet –
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 ?
I/O1. #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 into12. // 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 entered18. // 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. }
Example from booklet –
Inline Functions
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++
Motivation
Inline Functions
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
The solution
Inline Functions
1. #define ROUND (num) (int) ( (num) + 0.5)2.3. inline int round(double num)4. { 5. return (int) (num+0.5);6. }
Examples from booklet –
1. #define SQUARE (num) (num) * (num)2.3. inline double square(double num)4. { 5. return (num*num);6. }
Memory Allocation
Memory allocation is implemented with the command “new”.
No casting, sizeof is required (unlike C). For arrays allocation we will use “new[n]”.
Allocation
To free allocated memory, we will use the command “delete”.
For arrays, we will use “delete[ ]”.
Freeing
Memory allocation
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;
Example from booklet –
13. // depends on the options marked in the compiler ! ! !)14. for (int i=0; i<temp; i++)15. {16. // item is declared again and again17. // for every entry in the loop18. int item=GetItem (i) *13;19. ImportantVar+=item;20. }21. // The following line may be allowed, depending22. // on the options marked in the compiler ...23. cout<<i;24. ...25. }
Additional Improvements
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
Comments
Additional Improvements
Variables can be defined at any point in the code. Should be used wisely!!!!
Variable Definition
1. void main()2 . {3 . int ImportantVar; // controls for the nuclear explosion4. ...5. cout<<"Haide Sara";6. ...7. // We define here the variable temp to hold the outcome8. // of the function 'GoGetItf9. 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;,
Additional Improvements
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
Structs and enums Definition
1. struct Student2. {3. char* StudentName;4. int MoneyResources;5. // etc.6. };7.8. void main ( )9. {10. Student Dudu; / / in C: struct Student Dudu11. }