Object Oriented Programming Dr. Alon Schclar

Slides:



Advertisements
Similar presentations
C Language.
Advertisements

Programming Paradigms Introduction. 6/15/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved. L1:
Functions in C++. Functions  Groups a number of program statements into a unit & gives it a name.  Is a complete and independent program.  Divides.
Kernighan/Ritchie: Kelley/Pohl:
1 Chapter Three Using Methods. 2 Objectives Learn how to write methods with no arguments and no return value Learn about implementation hiding and how.
CSSE221: Software Dev. Honors Day 27 Announcements Announcements Projects turned in? Projects turned in? The 2 required Angel surveys are due by 9 pm tonight.
Computer Programming and Basic Software Engineering 4. Basic Software Engineering 1 Writing a Good Program 4. Basic Software Engineering 3 October 2007.
Rossella Lau Lecture 1, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 1: Introduction What this course is about:
CS 117 Spring 2002 Classes Hanly: Chapter 6 Freidman-Koffman: Chapter 10, intro in Chapter 3.7.
Starting out with C++1 Chapter 9 – Pointers Getting the address of a Variable Why do we have pointers? Indirection – difference between –Will you go out.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 10: Appendices.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
U NIVERSITY OF M ASSACHUSETTS A MHERST Department of Computer Science Computer Systems Principles C/C++ Emery Berger and Mark Corner University of Massachusetts.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
Guide To UNIX Using Linux Third Edition
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
C++ fundamentals.
OBJECT ORIENTED PROGRAMMING IN C++ LECTURE
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Object Oriented Programming Elhanan Borenstein copyrights © Elhanan Borenstein.
Computer Science and Software Engineering University of Wisconsin - Platteville 2. Pointer Yan Shi CS/SE2630 Lecture Notes.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Rossella Lau Lecture 1, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 1: Introduction What this course is about:
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Copyright  Hannu Laine C++-programming Part 1 Hannu Laine.
Week 14 - Monday.  What did we talk about last time?  Introduction to C++  Input and output  Functions  Overloadable  Default parameters  Pass.
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 6 Using Methods.
Object-Oriented Programming in C++
C++ Programming Basic Learning Prepared By The Smartpath Information systems
Object Oriented Programming Elhanan Borenstein Lecture #3 copyrights © Elhanan Borenstein.
Object Oriented Programming Elhanan Borenstein Lecture #10 copyrights © Elhanan Borenstein.
Week 2. Functions: int max3(int num1, int num2, int num3) {int result; result = max(max(num1,num2),num3); return result; } //max3.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved More about.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
C/C++ Basics. Basic Concepts Basic functions of each language: Input, output, math, decision, repetition Types of errors: Syntax errors, logic errors,
Introduction to C Programming Lecture 6. Functions – Call by value – Call by reference Arrays Today's Lecture Includes.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 16: Introduction to C++
Pointers *, &, array similarities, functions, sizeof.
CSC 143A 1 CSC 143 Introduction to C++ [Appendix A]
C++ Programming Lecture 13 Functions – Part V The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
CPS120: Introduction to Computer Science Lecture 16 Data Structures, OOP & Advanced Strings.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Slide 1 Chapter 6 Structures and Classes. Slide 2 Learning Objectives  Structures  Structure types  Structures as function arguments  Initializing.
1 CSE Programming in C++. 2 Overview Sign roster list Syllabus and Course Policies Introduction to C++ About Lab 1 Fill Questionnaire.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
Lecturer: Nguyen Thi Hien Software Engineering Department Home page: hienngong.wordpress.com Chapter 2: Language C++
Announcements Assignment 1 due Wednesday at 11:59PM Quiz 1 on Thursday 1.
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Object-Oriented Programming (OOP) and C++
Chapter 5 Arrays Copyright © 2016 Pearson, Inc. All rights reserved.
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
C++ Programming Michael Griffiths Corporate Information and Computing Services The University of Sheffield
Week 13 - Friday.  What did we talk about last time?  Server communications on a socket  Function pointers.
Introduction to C++ (Extensions to C)
C Programming Tutorial – Part I
Objectives Identify the built-in data types in C++
Object Oriented Programming
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
Stack Lesson xx   This module shows you the basic elements of a type of linked list called a stack.
(5 - 1) Object-Oriented Programming (OOP) and C++
Variables In programming, we often need to have places to store data. These receptacles are called variables. They are called that because they can change.
Chapter 15 Pointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types
Dr. Bhargavi Dept of CS CHRIST
(5 - 1) Object-Oriented Programming (OOP) and C++
Pointers, Dynamic Data, and Reference Types
Presentation transcript:

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 Inline Functions Memory Allocation Additional Improvements

Administration Course Page Books 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

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

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

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

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

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

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)

Chapter 3 Before Classes…

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);

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 }

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 ?

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 float or int to double // (there aren't any rules for this) }

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

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);

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

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

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

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. }

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. }

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. }

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 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");

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; 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 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

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.

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/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. }

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/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. }

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++

Inline Functions The solution Bigger exe – the same as macros 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

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. }

Memory Allocation Allocation Freeing 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[ ]”.

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;

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. }

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

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;,

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. }