Introduction to OOP. Contents:

Similar documents
Introduction to OOP. Contents:

IS 0020 Program Design and Software Tools

תכנות מונחה עצמים משחקים תשע"ו

Short Notes of CS201

CS201 - Introduction to Programming Glossary By

לתיכנות עם MATLAB Lecture 5: Boolean logic and Boolean expressions

לתיכנות עם MATLAB Lecture 5: Boolean logic and Boolean expressions

תוכנה 1. תרגול מספר 11: Static vs. Dynamic Binding מחלקות מקוננות Nested Classes

2015 Academic Challenge

מערכים שעור מס. 4 כל הזכויות שמורות דר ' דרור טובי המרכז האוניברסיטאי אריאל 1

Pointers, Dynamic Data, and Reference Types

הקלחמ ה תמרב ת ונ וכ ת (static members ) יליזרב דהוא Java תפשב ם דקת מ תונכת ביבא ל ת תטיסרבינוא

מבוא למדעי המחשב תרגול 8 רשימה משורשרת כללית, Comparator

תוכנה 1 סמסטר א' תשע"א

USING LAPACK SOLVERS FOR STRUCTURED MATRICES WITHIN MATLAB

Chapter 20 - C++ Virtual Functions and Polymorphism

CS3157: Advanced Programming. Outline

AN OVERVIEW OF C++ 1

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

CS201 Latest Solved MCQs

תוכנה 1 * לא בהכרח בסדר הזה

Chapter 19 - C++ Inheritance

Fast Introduction to Object Oriented Programming and C++

Chapter 19 C++ Inheritance


הנכות 1 תואיגש םע תודדומתהו תואלול,םי : כרעמ 2 לוגרת

Introduction to C++ Systems Programming

C++ Mini-Course. Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion. C Rulez!

מבוא לתכנות בשפת C. Tzachi (Isaac) Rosen

תוכנה 1 * לא בהכרח בסדר הזה

הנכות 1 תואיגש םע תודדומתהו תואלול,םיכרעמ : לו 2 גרת

Introduction to Programming in C תרגול 8

Classes: A Deeper Look

COMP322 - Introduction to C++

Midterm Review. PIC 10B Spring 2018

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

Practical Session - Heap

A brief introduction to C++

תוכנה 1 תרגול 2: מערכים, מבני בקרה ושגיאות

Chapter 15 - C++ As A "Better C"

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Chapter 1: Object-Oriented Programming Using C++

Introduction to Programming session 24

Lecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology

Come and join us at WebLyceum

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

תוכנה 1 תרגול 2: מערכים ומבני בקרה

Object-Oriented Programming Concepts

ASP.Net Web API.

C++ Mini-Course. Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion. C Rulez!

מבוא לתכנות תוכנית שעור מס. 1 1 דר' דרור טובי, המרכז האוניברסיטאי אריאל בשומרון.

EL2310 Scientific Programming

Java פעולות עוברות בירושה סביבת יסודות מדעי המחשב נספח הורשה

Introducing C++ to Java Programmers

הנכות 1 םוכיס לוגרת 13 1

pointers & references

Computer Programming A תרגול 9

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

Algorithms. Intro2CS week 5

Chapter 9 - Object-Oriented Programming: Inheritance

תוכנה 1 * לא בהכרח בסדר הזה

C++ Memory Map. A pointer is a variable that holds a memory address, usually the location of another variable in memory.

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

היצביט ומ - ןוכית ת וי נבת

CS11 Intro C++ Spring 2018 Lecture 1

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

Introduction to the C programming language

מצליחה. 1. int fork-bomb() 2. { 3. fork(); 4. fork() && fork() fork(); 5. fork(); printf("bla\n"); 8. return 0; 9. }

Introduction to Programming Using Java (98-388)

Introduction to the C programming language

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

CS201- Introduction to Programming Current Quizzes

For Teacher's Use Only Q No Total Q No Q No

CS201 Some Important Definitions

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

Module 7 b. -Namespaces -Exceptions handling

Tutorial 10. Introduction to C++ שימו

Programming, numerics and optimization

C++ Classes, Constructor & Object Oriented Programming

Object-Oriented Programming for Scientific Computing

תוכנה 1 ומחלקות פנימיות

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

CSE 303: Concepts and Tools for Software Development

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

ספרית התבניות הסטנדרטית (STL) כתיבת אלגוריתמים גנריים מצביעים חכמים. .vector. list iterator נכיר תחילה את האוסף הפשוט ביותר בספריה

A Tour of the C++ Programming Language

6.096 Introduction to C++ January (IAP) 2009

CS250 Final Review Questions

C++_ MARKS 40 MIN

Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

GEA 2017, Week 4. February 21, 2017

CS250 Final Review Questions

הנכות 1 םוכיס לוגרת 14 1

CSCI 171 Chapter Outlines

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

תוכנה 1 בשפת Java נושאים שונים בהורשה רובי בוים ומתי שמרת בית הספר למדעי המחשב אוניברסיטת תל אביב

CS250 Intro to CS II. Spring CS250 - Intro to CS II 1

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

Transcription:

11/9/2014 Introduction to OOP. Any fool can write code that a computer can understand. Good programmers write code that humans can understand. (Martin Fowler) Presented by: Contents: History; C refrain; The OOP basis; Getting started. 11/9/2014 2 1

The C and C++ development C was developed from BCPL and B languages. The languages hasn t different types definition, so each variable (char, short or long) is stored as one cell (word) in physical memory. However, the C language is a program language with different build-in types C++ - C based program language which was developed in Bell laboratory in the beginning 80 s. The C++ is support OOP (Object Oriented Programming) 11/9/2014 4 Why C++? a b 11/9/2014 5 2

What are the memory segments? The text segment (often called code segment) is where the compiled code of the program itself resides. The two other sections from the code segment in the memory are used for data 11/9/2014 13 What is stack? The stack is the section of memory that is allocated for automatic variables within functions. declaration with no static or external specifier defines an automatic variable Data is stored in stack using the Last In First Out (LIFO) method. This means that storage in the memory is allocated and deallocated at only one end of the memory called the top of the stack. Stack is a section of memory and its associated registers that is used for temporary storage of information in which the most recently stored item is the first to be retrieved. 11/9/2014 14 3

What is heap? Heap is an area of memory used for dynamic memory allocation. Blocks of memory are allocated and freed in this case in an arbitrary order. The pattern of allocation and size of blocks is not known until run time. Heap is usually being used by a program for many different purposes. 11/9/2014 15 What is heap and stack? The stack is a place in the computer memory where all the variables that are declared and initialized before runtime are stored The heap is the section of computer memory where all the variables created or initialized at runtime are stored. The stack is much faster than the heap but also smaller. 11/9/2014 16 4

What is heap and stack? int x; void main() int y; char str; str = malloc(50); // static stack storage // dynamic stack storage // dynamic stack storage // allocates 50 bytes of // dynamic heap storage size = calcsize(10); // dynamic heap storage, // if function defined // in DLL 11/9/2014 17 Arrays and Pointers Static array: are allocated on the stack. int ifibarray[10]; int k; ifibarray[0] = 1; ifibarray[1] = 1; for (k = 2; k < 10; k++) ifibarray[k] = ifibarray[k - 1] + ifibarray[k - 2]; 11/9/2014 18 5

Dynamic Memory Allocation The static arrays allocates on the stack which has a limited size. When large arrays are needed we have to use dynamic memory allocation. Using this way the arrays allocates on the heap int n; int *iarrayp; n = 1000; iarrayp = (int *) malloc (sizeof(int) * n); if (iarrayp == NULL) abort(); /* In case the allocation has failed */ iarrayp[n-1] = 1; : Free (iarrayp); 11/9/2014 19 Arrays and Pointers A pointer is a variable whose size is the same as the size of int and can store the address of another variable float fsum; float *fsump; fsump = NULL; // definition of a variable // definition of a pointer // - i.e. the pointer is currently not // pointing on any variable fsump = &fsum; // fsump obtains the address of fsum fsum = *fsump; // de-reference a pointer or i.e. obtain // the variable in that address 11/9/2014 20 6

Arrays and Pointers Pointers play important role when passing parameters to functions. void swap (int a, int b) int temp = a; a = b; b = temp; } void main() int x = 3, y = 4; swap(x, y); } The function on the left don t really change the values of x and y. In C function arguments are passed by value copy each function argument to stack. The solution is to pass the address of the variables to the function. 11/9/2014 21 void swap (int *aptr, int *bptr) int temp = *aptr; *aptr = *bptr; *bptr = temp; } void main() int x = 3, y = 4; swap(&x, &y); } Compound data types It is possible to expand the data type repository by defining structures. A structure is used to pack together several fields that are conceptually related: struct Date int iday; int imonth; int iyear; } DataStr; // Structure objects definition struct Date date; date.iday = 31; date.imonth = 12; date.iyear = 1999; // Pointer to structure struct Data *datep = &date; (*datep).iday = 21; // or easier datep->iday = 21; 11/9/2014 22 7

Compound data types It is very convenient to define enumeration types. An enumeration variable is an integer, which have a limited range of designated values: enum ChessBoardColour Black; White }; enum ChessBoardColour col; : If (col == Black) : }; By default the first enum value is 0, and each next is 1 more then previous, but It s possible to assign different integer values: enum _ErrorCode AllOK = 1; FileNotFound = -1; IllegalFileFormat = -2; 11/9/2014 } 23 Compound data types By default the first enum value is 0, and each next is 1 more then previous, but It s possible to assign different integer values: enum _ErrorCode AllOK = 1; FileNotFound = -1; IllegalFileFormat = -2; } It s possible to use the typedef command in order to define more convenient name for our data types: typedef enum _Errorcode Errorcode; 11/9/2014 24 8

Recursion In C function can call itself. The following function calculates recursively the value of n!: int factorial (int n) if (n <= 0) return(1); else return(n*factorial(n-1)); } 11/9/2014 25 Variable scope Local variable is defined inside a function and destroyed then function terminates the variable created in the stack Global variables are created before the first instruction in the main. It is executed and destroyed only after the program terminates the variable created on the data segment The keyword static before global variable and function makes it available only within the file It is defined in. 11/9/2014 26 9

Variable scope The keyword static before a variable declaration inside a function: the variable created the first time the function is called and isn t destroyed when it terminates The keyword register before a variable declaration inside a function. The register variables may be only local. the variable created in the CPU register The keyword volatile before a variable declaration behaves like register. It prevents optimization operations on variable. However allows to allocate variable on the memory instead of register. the variable created in the memory 11/9/2014 27 C vs. C++ Same syntax, operators, expressions, data types, structures, arrays, cycles, functions and pointers; C++ has some new keywords: class, delete, friend, inline, new, protected, public and et. C++ supports object oriented programming 11/9/2014 29 10

11/9/2014 Introduction to OOP אותנו הסובב העולם את תופסים אנו פרח, כלב, ציפור, למשל: )אובייקטים(, אדם וכו'. בתור עצמים מכונית, בית, לכל עצם יש מאפיינים, למשל: גודל, צורה, צבע, משקל וכו'. לכל עצם יש פעולות )מתודות, פונקציות( שמאפיינות אותו. למשל: העצם אדם יכול לנוע, לדבר, לאכול וכו', העצם מכונית יכול לנוע, לצפצף, להאיר את הדרך וכו'. אנו לומדים על העצמים תוך כדי צפייה על המאפיינים ועל הפעולות שהם יכולים לבצע. 11/9/2014 30 Introduction to OOP 11/9/2014 31 תכנות מונחה עצמים Progamming( )OOP,Object Oriented הוא תכנות הפועל בצורה דומה לזו שבה פועל מוח האדם הוא ממדל את "העולם" בעזרת עצמים. ניתן לרכז )לכמס, )encapsulate את כל המאפיינים והפונקציות השייכים לעצם מסויים למחלקה )class( על שמו. היחס בין עצם )object( ומחלקה )class( הוא היחס בין עוגה לתבנית עוגה. עצמים שונים יכולים להיות בעלי מאפיינים משותפים ו/או פעולות משותפות. למשל גם העצם אדם וגם העצם מכונית יכולים לנוע )למרות זאת תנועת האדם שונה מתנועת המכונית(. ניתן להגדיר מבנה היררכי של עצמים, עצמים כלליים יותר יהיו "האבות" של עצמים כלליים פחות ויוכלו לתת )להוריש, )inherit להם חלק מתכונותיהם. למשל העצם תוכי יכול לקבל מאפיינים מהעצם ציפור שכן תוכי הוא סוג של ציפור. 11

The major properties of OOP ריכוזיות - Encapsulation / הסתרת מידע hiding Information ההכלה מחלקתית של כל המשאבים )קוד ונתונים( הדרושים לשם תיפקודו של העצם. עצמים אחרים יכולים רק להגיע לממשק, אותו העצם רוצה לפרסם כלפיהם, אך אין להם יכולת לדעת איך דברים נעשים בצורה פנימית. למשל העצם אדם יכול להשתמש בפעולת התנועה )נסיעה( של העצם המכונית )כלומר האדם יכול לנסוע במכונית( בלי להבין איך פועל המנוע בעצם זה. תורשה - Inheritance העברה של משאבים ממחלקה אחת למחלקה הנגזרת ממנה. בצורה זו אין צורך לחזור כמה פעמים על תכונות שמשותפות למחלקת היס ולמחלקה הנגזרת. למשל: המחלקה שולחן נגזרת מהמחלקה רהיט. ריבוי צורתיות - Polymorphism היכולת להקנות משמעויות שונות עבור פעולות עם שם זהה המתבצעות עבור עצמים שונים. למשל: פעולת "פתיחה" מקבלת משמעות שונה אם העצם המדובר הוא דלת או שהעצם המדובר הוא קופסת שימורים. 11/9/2014 32 Input/Output using namespace std; ------------------------------------------------------------ int n, fact; cin >> n; fact = factorial(n); cout << n <<! = << fact << endl; Notes: cin & >> and cout << Both operators can be applied sequentially, and are left associative; One can send any type of basic data type to cout or obtain it from cin; It is possible to differentiate between normal program output, which is sent to cout, and error output, which is sent to ceer (similar to stdout and stderr in C); The endl is a global manipulator, and means end of line (endl = \n ) 12

Structures vs. Classes Working with complex numbers in C: struct _Complex float re // The real part. float im; // The imaginary part }; typedef struct _Complex Complex; #include <math.h> /* Calculate the amplitude and argument of Complex number */ double magnitude (Complex z) return(sqrt (z.re*z.re+z.im*z.im)); } double argument (Complex z) return(atan2 (z.im, z.re)) } Working with complex numbers in C++: class Complex private: float Re // The real part. float Im; // The imaginary part pablic: // Get the real and imaginary part float getreal() return (Re);} float getimag() return (Im);} // Set the complex number x + iy void set (float x, float y); Re = x; Im = y; } }; ---------------------------------- Complex z; z.set(3,4); cout << z= << z.getreal(); cout << +i << z.getimeg()<<endl; z.re = 5; ERROR!!! is a private data Function Overloading C++ supports writing more than one function with the same name but different argument lists. This could include: different data types different number of arguments The advantage is that the same apparent function can be called to perform similar but different tasks. The following will show an example of this. 13

Function Overloading void swap (int *a, int *b) ; void swap (float *c, float *d) ; void swap (char *p, char *q) ; int main ( ) int a = 4, b = 6 ; float c = 16.7, d = -7.89 ; char p = 'M', q = 'n' ; swap (&a, &b) ; swap (&c, &d) ; swap (&p, &q) ; } void swap (int *a, int *b) int temp; temp = *a; *a = *b; *b = temp; } void swap (float *c, float *d) float temp; temp = *c; *c = *d; *d = temp; } void swap (char *p, char *q) char temp; temp = *p; *p = *q; *q = temp; } Example 1: The class definition and the advantages of Encapsulation 11/9/2014 43 מחלקה )class( היא התבנית של העצם והיא יכולה להכיל מאפיינים ופונקציות של העצם. המשתנים והפונקציות יכולים לקבל אחת משלוש הרשאות: Public יש נגישות לפונקציות ולמשתנים אלו גם מתוך וגם מחוץ לעצם. Private יש נגישות לפונקציות ולמשתנים אלו רק מתוך העצם, אך לא מחוצה לו, אלא רק לעצמים שמוגדרים כעמיתים.)friends( Protected השראת ביניים. יש נגישות מתוך העצם ומתוך העמיתים שלו כמו כן יש נגישות מתוך נגזרותיו של העצם והעמיתים שלהם. 14

Example 1: The class definition and the advantages of Encapsulation פונקציות הבונה )Constructor( היא פונקצייה מחלקתית שנקראת אוטומטית עם יצירת העצם. בדרך כלל משתמשים בפונקציה זו על מנת לאתחל את משתני המחלקה. פונקציית הבונה היא בעלת שם זהה לשמה של המחלקה. פונקציות המפרק )Destructor( היא פונקציה מחלקתית שנקראת אוטומטית עם פירוק העצם. )פירוק העצם מתרחש למשל וף התוכנית(. פונקציית המפרק היא בעלת שם זהה לשמה של המחלקה, אך היא בעלת הסימן ~ לפני שמה. 11/9/2014 44 1 // Time class. 2 #include <iostream> 3 #include <iomanip> 4 using namespace std; 5 6 7 8 9 // Time class definition 10 class Time 11 public: 12 Time(); // constructor 13 void settime( int, int, int ); // set hour, minute, second 14 void printtime(); // print universal-time format 15 16 private: 17 int hour; // 0-23 (24-hour clock format) 18 int minute; // 0-59 19 int second; // 0-59 20 21 }; // end class Time נתונים ופונקציות בעלי הרשאה ציבורית נתונים ופונקציות בעלי הרשאה פרטית הגדרת ה- class Time 15

23 // Time constructor initializes each data member to zero and פונקציית פונקציית הבונה state מאתחלת נתון // ensures all Time objects start in a consistent 24 25 Time::Time() בנאי בעל הרשאה פרטית )private( ל- 0 26 27 hour = minute = second = 0; 28 } // end Time constructor Constructor initializes 29 private data members פונקצייה 30 // set new Time value using universal to 0. time, perform validity לשינוי בדיקת תקינות 31 // checks on the data values and set invalid values to zero 32 void Time::setTime( int h, int m, int s ) 33 34 hour = ( h >= 0 && h < 24 )? h : 0; 35 minute = ( m >= 0 && m < 60 )? m : 0; 36 second = ( s >= 0 && s < 60 )? s : 0; 37 } // end function settime 38 39 // print Time 40 void Time::printTime() 41 fill character field width 42 cout << setfill( '0' ) << setw( 2 ) << hour << ":" 43 << setw( 2 ) << minute << ":" << setw( 2 ) << second; 44 }// end function printtime field width הזמן פונקצייה להדפסת הזמן נתונים בעלי הרשאה פרטית )private( 45 int main() 46 הצהרה על המשתנה t להיות אובייקט מטיפוס ה- class הנקרא Time 47 Time t; // instantiate object t of class Time 48 49 // output Time object t's initial value 50 cout << "The initial time is "; 51 t.printtime(); // 00:00:00 52 שימוש בפונקציית חבר בעל הרשאה ציבורית (public) 53 t.settime( 13, 27, 6 ); // change time כדי להדפיס את הזמן 54 55 // output Time object t's new values 56 cout << "\n\nthe time after settime is "; 57 t.printtime(); // 13:27:06 שימוש בפונקציית חבר בעל 58 cout << endl; הרשאה ציבורית (public) 59 כדי לשנות את הזמן 60 return 0; 61 } // end main The initial time is 00:00:00 The time after settime is 13:27:06 16

Example 2: Inheritance y עיגול )x,y,r) r )x,y) גליל אליפסי )x,y,r,h) x y נקודה )x,y) )x,y) x גליל )x,y,r,h) r h קו )x,y,x1,y1) קו )x,y,x1,y1) y )x,y) )x1,y1) )x,y) 48 לעצם עיגול וגם לעצם קו. 11/9/2014 x לפי תכונת התורשה ניתן לבנות מבנה היררכי של עצמים. Base class מספק נתונים או פונקציות ל- class -ים אחרים. Derived class יורש נתונים או פונקציות מ- class -ים אחרים. דוגמא: העצם גליל יורש את תכונותיו של העצם עיגול שיורש את תכונותיו של העצם נקודה. מצד שני: העצם נקודה מוריש את תכונותיו גם File point.h: 1 #ifndef POINT_H 2 #define POINT_H 3 4 class Point 5 public: 6 Point( int = 0, int = 0 ); // default constructor 7 void setx( int ); // set x in coordinate pair 8 int getx() const; // return x from coordinate pair 9 void sety( int ); // set y in coordinate pair 10 int gety() const; // return y from coordinate pair 11 void print() const; // output Point object 12 13 protected: 14 int x; // x part of coordinate pair 15 int y; // y part of coordinate pair 16 }; // end class Point 17 18 #endif Class definition בעלי הרשאה ציבורית )public( בעלי הרשאה מוגנת )protected( Keyword const will ban getx(), gety() and print() in class Point from being anything which can attempt to alter any member variables in the object הערה: שימו לב לחלוקה לקבצים h. ו- cpp. שלא הייתה קיימת בדוגמא הקודמת. 17

File point.cpp: 1 #include <iostream> 2 #include "point.h" // Point class definition 3 // default constructor 4 Point::Point( int xvalue, int yvalue ) 5 6 x = xvalue; 7 y = yvalue; 8 } // end Point constructor 9 // set x in coordinate pair 10 void Point::setX( int xvalue ) 11 12 x = xvalue; // no need for validation 13 } // end function setx 14 // return x from coordinate pair 15 int Point::getX() const 16 17 return x; 18 } // end function getx 19 // set y in coordinate pair 20 void Point::setY( int yvalue ) 21 22 y = yvalue; // no need for validation 23 } // end function sety 24 // return y from coordinate pair 25 int Point::getY() const 26 27 return y; 28 } // end function gety 29 // output Point2 object 30 void Point::print() const 31 32 cout << '[' << x << ", " << y << ']'; 33 } // end function print Constructor function פונקציה לשינוי x פונקציה לקבלת ערכו של x פונקציה לשינוי y פונקציה לקבלת ערכו של y Printing x & y File circle.h: 1 #ifndef CIRCLE_H 2 #define CIRCLE_H 3 class נקודה ה- class 4 מוריש את תכונותיו #include "point.h" // Include point class definition 5 עיגול ל- class 6 class Circle : public Point בעלי הרשאה ציבורית 7 )public( 8 public: 9 // default constructor 10 Circle ( int = 0, int = 0, double = 0.0 ); 11 void setradius( double ); // set radius 12 double getradius() const; // return radius 13 double getarea() const; // return area 14 void print() const; // output Circle object 15 16 private: 17 double radius; // Circle's radius 18 19 }; // end class Circle 20 #endif Connection to the base בעלי הרשאה פרטית )private( 18

וx File circle.cpp פונקציית הבנאי קוראת לפונקציית (באופן מוסתר( 1 #include <iostream> Base class הבנאי של ה- 2 #include "circle.h" // Include circle class definition 3 4 // default constructor 5 Circle::Circle( int xvalue, int yvalue, double radiusvalue ) 6 7 x = xvalue; ניתן לשנות את x ו- y מאחר והם 8 y = yvalue; הוכרזו כ- protected 9 setradius( radiusvalue ); )הנקרא (Point ב class Base 10 } // end Circle constructor 11 // set radius 12 void Circle::setRadius( double radiusvalue ) 13 14 radius = ( radiusvalue < 0.0? 0.0 : radiusvalue ); 15 } // end function setradius 16 // return radius 17 double Circle::getRadius() const 18 19 return radius; 20 } // end function getradius 21 // calculate and return area 22 double Circle::getArea() const 23 24 return 3.14159 * radius * radius; 51 } // end function getarea 25 // output Circle object 26 void Circle::print() const 27 28 cout << "Center = [" << x << ", " << y << ']' 29 << "; Radius = " << radius; 30 } // end function print פונקציית בנאי פונקצייה לשינוי הרדיוס פונקצייה לקבלת ערכו של הרדיוס פונקצייה לקבלת השטח ניתן להשתמש ב- x ו- y מאחר והם הוכרזו כ- protected ב- class Base )הנקרא (Point הדפסת y,x והרדיוס File CircleTest.cpp: 1 #include <iostream> יצירת האובייקט MyCircle 2 #include <iomanip> 33 #include "circle.h" // Circle class definition 44 שימוש בפונקציות 55 int main() שנורשו מ- Point על 66 מנת לגשת לנתונים 77 Circle MyCircle( 37, 43, 2.5 ); // instantiate Circle object 99 // display point coordinates - y )הם בהרשאת 10 cout << "X coordinate is " << MyCircle.getX() )protected קבלת הרדיוס ע"י שימוש בפונקציה getradius של MyCircle 16 MyCircle.setRadius( 4.25 ); // set new radius שימוש בפונקציות שנורשו 17 18 // display new point value מ- Point על מנת לשנות את 19 cout << "\n\nthe new location and radius of circle are\n"; הנתונים x ו- y 20 MyCircle.print(); )הם בהרשאת )protected 21 22 // display Circle's area שימוש בפונקציה 23 cout << "\narea is " << MyCircle.getArea(); MyCircle של setradius 25 cout << endl; 27 return 0; // indicates successful termination על מנת לשנות את נתון 29 } // end main הרדיוס )שהוא בעל השראת )private 11 13 14 << "\ny coordinate is " << MyCircle.getY() MyCircle.setX( 2 ); // set new x-coordinate 12 15 << "\nradius is " << MyCircle.getRadius(); MyCircle.setY( 2 ); // set new y-coordinate Output after executing שימוש בפונקציה getarea של MyCircle על מנת להדפיס את נתוני העיגול X coordinate is 37 Y coordinate is 43 Radius is 2.5 שימוש בפונקציה Print של MyCircle על מנת להדפיס את נתוני העיגול The new location and radius of circle are Center = [2, 2]; Radius = 4.25 Area is 56.74 19

Dynamic memory זיכרון דינאמי הוא חלק חשוב בשביל כמעט כל המתכנתים בעולם; C++ מספקת לנו שני אופרטורים בזיכרון דינאמי: new - מאתר )תופס( זיכרון ומחזיר פוינטר להתחלה; ;new משחרר את הזיכרון שאותר מקודם ע"י - delete אופרטורים אלו משמשים לתפוס זיכרון ולשחרר זיכרון בזמן ריצה )פעולה (. למרות ש++ C תומכת בהקצאת זיכרון דינאמי גם ע''י בפונקציות ו- delete ; new להשתמש באופרטורים נהוג ו- free, malloc פונקציות malloc ו- free נכללות בגלל שפת C שהיא חלק משפת++ C. יתרונות של :new בצורה אוטומטית מאתר מספיק זיכרון בכדי להחזיק אובייקט מסוג ספציפי. לא צריך להשתמש באופרטור,sizeof מכוון שהגודל מותאם אוטומטית אוטומטית מחזיר פוינטר לאותו סוג ספציפי 11/9/2014 54 ptr = new Type; delete ptr; 1 #include <iostream.h> 2 #include <new.h> 3 int main ( ) 4 5 int *ptr; 6 // memory allocation for variable with size int 7 ptr = new int; 8 *ptr = 100; 9 cout<< At" << ptr <<" "; 10 cout<<" is the value " << *ptr <<"\n"; 11 delete ptr; 12 return 0; 13 } At 0xabcdef00 is the value 100 20

Memory allocation for arrays 1 #include <iostream.h> 2 #include <new.h> 3 int main ( ) 4 int *array, i; 5 // memory allocation for array of integers with length 10 6 array = new int [10]; ptr = new Array_Type[Size]; delete [ ] ptr; 7 for ( i = 1; i < 10; i++) 8 9 *array++ = i; 10 cout << array[i] << "\n"; 11 } 12 delete [] array; 13 return 0; 14 } 11/9/2014 56 1 2 3 4 5 6 7 8 9 10 Pass by Pointer and pass by Reference in C++ // Illustration of pass by pointer #include <iostream.h> void square (int *x) *x = (*x)*(*x); } // Illustration of pass by reference #include <iostream.h> // x becomes a reference parameter void square (int &x) // no need to write *x = (*x)*(*x); x = x * x; } int main ( ) int num = 10; square(&num); // Value of num is 100 cout << " Value of num is "<< num; return 0; } int main ( ) int num = 10; square(num); // Value of num is 100 cout << "Value of num is << num; return 0; } 11/9/2014 57 21

More about reference variables Reference variables are not applicable only to function parameters. You can have them in other places of the program as well. Consider the following program: #include <iostream.h> int main( ) int x; int &ref = x; //ref is a reference variable x=5; cout << endl << x << " << ref; x++; cout << endl << x << " << ref; ref++; cout << endl << x << " << ref; cout << endl << &x << endl << &ref; return 0; } 5 5 6 6 7 7 0x0065FDF4 0x0065FDF4 The reference variables provides different names same variable. They both refers to the same memory address. The address of both ref and x is the same. 11/9/2014 58 Example3: Polymorphism Functions: 1. Breath 2. Speak Dog Pet Example Cat לפי תכונת הפולימופיזם, המצביע יכול ל- Class Base הרפרנס או כאשר שונות בדרכים להתנהג מרובה. בשימוש נמצא הוא לגשת למשל נוכל זו בצורה לפונקציה ב- class הנגזר במקום לפונקציה ב- class היס. ב-++ C הדבר נעשה תוך שימוש )מה וירטואליות בפונקציות של הפולימורפיות שיגדיר את העצם(. 11/9/2014 59 22

1 #include <iostream> 2 #include <string> 3 4 class Pet 5 6 public: 7 // Constructors, Destructors 8 Pet () } 9 virtual ~Pet () } 10 11 // General methods 12 void breath(); 13 virtual void speak(); 14 };// end class pet 15 16 void Pet::breath() 17 18 cout << Gasp" << endl; 19 } 20 21 void Pet::speak() 22 23 cout << "Growl" << endl; 24 } הגדרת המחלקה "חיית מחמד" 1. פונקציות בנאי ופונקציית הורס וירטואלית 2. פונקציית נשימה 3. פונקציית דיבור וירטואלית In object-oriented programming, a virtual function or virtual method is a function or method whose behavior can be overridden within an inheriting class by a function with the same name פונקציית נשימה פונקציית דיבור Dog Pet Cat "כלב" שיורשת 1 class Dog: public Pet "חיית מחמד" 2 3 public: 4 Dog() } 5 6 void speak(); 7 }; 8 void Dog::speak() "כלב" המחליפה את 9 10 cout << Hav-Hav" << endl; 11 } 12 class Cat: public Pet "חתול" שיורשת 13 "חיית מחמד" 14 public: 15 Cat() } 16 17 void speak(); 18 }; 19 void Cat::speak() "חתול" המחליפה את 20 21 cout << "Meow" << endl; 22 } 23 void chorus(pet pet, Pet *petptr, Pet &petref) 24 25 pet.speak(); petptr->speak(); petref.speak(); Dog 28 } הגדרת המחלקה את המחלקה 1. פונקציות בנאי 2. פונקציית דיבור חדשה )פונקציית נשימה הורשה כבר( פונקציית דיבור חדשה למחלקה פונקציית הדיבור הישנה של ה- Class "חיית מחמד" הגדרת המחלקה את המחלקה 1. פונקציות בנאי 2. פונקציית דיבור חדשה )פונקציית נשימה הורשה כבר( פונקציית דיבור חדשה למחלקה Pet פונקציית הדיבור הישנה של המחלקה "חיית מחמד" הפונקציית "מקהלה" מקבלת את האובייקט Cat "חיית מחמד", מצביע אליו ורפרנס אליו קבלת רפרנס לעצם קבלת מצביע לעצם קבלת העצם 23

אובייקט חדש יצירת מצביע למחלקת היס יצירת ptr המצביע ואיתחול 1 int main() שיצביע עליו כך 2 3 Pet *ptr; //Pointer to base class 4 5 ptr = new Pet; cout << "Pet Created" << endl; 6 cout << "Pets singing" << endl; רפרנס מצביע אובייקט אובייקט = *ptr 7 chorus(*ptr,ptr,*ptr); 8 cout << endl << endl; מצביע = ptr 9 delete ptr; //Prevent memory leaks 10 11 ptr = new Dog; cout << Dog Created" << endl; 12 cout << Dogs singing" << endl; רפרנס מצביע אובייקט אובייקט = *ptr 13 chorus(*ptr,ptr,*ptr); מצביע = ptr 14 cout << endl << endl; 15 delete ptr; //Prevent memory leaks 16 17 ptr = new Cat; cout << "Cat Created" << endl; 18 cout << Cats singing" << endl; רפרנס מצביע אובייקט 19 chorus(*ptr,ptr,*ptr); 20 cout << endl << endl; 21 delete ptr; //Prevent memory leaks 22 return 0; 23 } //End main אובייקט = *ptr מצביע = ptr Pet Created Pets singing Growl Growl Growl Dog Created Dogs singing Growl Hav-Hav Hav-Hav Cat Created Cats singing Growl Meow Meow כאשר מעבירים ארגומנט value" "by )כמו הארגומנט הראשון של פונקציית המקהלה( מועבר למעשה העתק של אותו ארגומנט. במצב זה הקומפיילר מכין מקום שמספיק עבור העצם "חיית מחמד" ואז מנסה להעתיק לתוכו את העצם "כלב" )או "חתול"(. מכיוון שעצמים אלו גדולים מהעצם "חיית מחמד" מתבצע חיתוך,)slicing( כך שרק החלק של העצם "כלב" )או של העצם "חתול"( הזהה לעצם "חיית מחמד" יעותק. כאשר קוראים לפונקציית הדיבור במקרה זו, פונקציית הדיבור של העצם "חיית מחמד" היא זו שתופעל. במקרים של הארגומנט שני והשלישי של פונקציית המקהלה, כאשר מעבירים פוינטר )כתובת( / רפרנס מופעלת פונקציית הדיבור של העצם "כלב" )או של העצם "חתול"(. עקב הכרזת פונקציית הדיבור כוירטואלית, איפשרנו את ההתנהגות הפולימורפית של המצביעים או הרפרנסים של מחלקת היס "חיית מחמד" כלומר ניתן בעזרתם להגיע לפונקציית הדיבור של המחלקות הנגזרות ממנה. Pet Created Pets singing Growl Growl Growl Dog Created Dogs singing Growl Hav-Hav Hav-Hav Cat Created Cats singing Growl Meow Meow 24

Structure of a Function M-file»output_value = mean(input_value) Command Line Syntax Keyword: function Function Name (same as file name.m) Output Argument(s) Input Argument(s) Online Help MATLAB Code function y = mean(x) % MEAN Average or mean value. % For vectors, MEAN(x) returns the mean value. % For matrices, MEAN(x) is a row vector % containing the mean value of each column. [m,n] = size(x); if m == 1 m = n; end y = sum(x)/m; What are MEX-files? MEX stands for MATLAB Executable. MEX-files are a way to call your custom C/C++ routines directly from MATLAB as if they were MATLAB built-in functions. Mex-files can be called exactly like M- functions in MATLAB. Here, all code examples will be presented in C. 11/9/2014 66 25

Reasons for MEX-files The ability to call large existing C/C++ routines directly from MATLAB without having to rewrite them as M-files. Speed: you can rewrite bottleneck computations (like for-loops) as a MEX-file for efficiency. 11/9/2014 67 The gateway routine The name of the gateway routine must be mexfunction. prhs - an array of right-hand input arguments. plhs - an array of left-hand output arguments. nrhs - the number of right-hand arguments, or the size of the prhs array. nlhs - the number of left-hand arguments, or the size of the plhs array. void mexfunction (int nlhs, mxarray *plhs[], int nrhs, const mxarray *prhs[]) /* more C/C++ code... */ 11/9/2014 69 26

Some important points The parameters prhs, plhs, nrhs and nlhs are required. The header file, mex.h, that declares the entry point and interface routines is also required. The name of the file with the gateway routine will be the command name in MATLAB. The file extension of the MEX-file is platform dependent. The mexext function returns the extension for the current machine MATLAB is 1-based and C is 0-based 11/9/2014 71 EXAMPLE: hellomatlab.c The function description: If a string is passed as an input, it displays the string as output If no inputs are passed, a default string is passed as an output An improper call (improper number of inputs/outputs) returns an error message as the output /* hellomatlab.c */ # include "mex.h" void mexfunction( int nlhs, mxarray *plhs[], int nrhs, const mxarray *prhs[]) } if (nrhs < 1) plhs[0] = mxcreatestring("default String: Hello Users"); else if (nrhs > 1) mexerrmsgtxt("improper Inputs argument: Please pass 1 or no input arguments"); else plhs[0] = mxduplicatearray(prhs[0]); 11/9/2014 72 27

C compiler http://www.mathworks.com/support/compilers/r2013b/index.html? sec=win64 11/9/2014 73 EXAMPLE: hellomatlab.c Setup the C-compiler to generate MEX-files Compile the hellomatlab.c and build the binary MEX-file Call the hellomatlab function with one input argument. See the results. Call the hellomatlab function without inputs. Call the hellomatlab function with improper number of inputs /* hellomatlab.c */ 1.>> mex setup 2.>> mex hellomatlab.c 3.>> hellomatlab (['My first MEX-file works!']) ans = My first MEX-file works! 4.>> hellomatlab ans = Default String: Hello Users 5.>> hellomatlab (['My first MEX-file works!'],['aaa']) Error using hellomatlab Improper Inputs argument: Please pass 1 or no input arguments 11/9/2014 74 28

THE mex SCRIPT SYNTAX mex help displays the help file for mex mex setup select or change the compiler configuration mex filenames compiles and links one or more C/C++ source files specified in filenames into a shared library called a binary MEX-file from MATLAB. mex options filenames compiles and links one or more source files specified in filenames using one or more of the specified command-line options 11/9/2014 75 Working with mxarrays [a,b]=timestwo([1 2 3 4; 5 6 7 8], 8) /* timestwo.c */ /* Create an mxarray for the output */ #include "mex.h" plhs[i] = mxcreatedoublematrix(m, void mexfunction(int nlhs, mxarray n, mxreal); *plhs[], int nrhs, const mxarray /* Get the data passed in */ *prhs[]) data1 = mxgetpr(prhs[i]); /* Create an array for the output's data */ int i, j, m, n; data2 = (double *) mxmalloc(m*n * double *data1, *data2; if (nrhs!= nlhs) sizeof(double)); /* Put data in the array */ mexerrmsgtxt("the number of input and output arguments must be the for (j = 0; j < m*n; j++) same."); data2[j] = 2 * data1[j]; /* Assign the data array to the output for (i = 0; i < nrhs; i++) array */ mxsetpr(plhs[i], data2); /* Find the dimension of the data */ } m = mxgetm(prhs[i]); n = mxgetn(prhs[i]); } 11/9/2014 76 29

Working with integers int index; index=(int)mxgetscalar(prhs[1]); 11/9/2014 77 An additional examples #include "mex.h" void timestwo(double y[], double x[]) y[0] = 2.0*x[0]; } void mexfunction(int nlhs, mxarray *plhs[], int nrhs, const mxarray *prhs[]) double *x, *y; int mrows, ncols; /* Check for proper number of arguments. */ if (nrhs!= 1) mexerrmsgtxt("one input required."); } else if (nlhs > 1) mexerrmsgtxt("too many output arguments"); } /* The input must be a noncomplex scalar double.*/ mrows = mxgetm(prhs[0]); ncols = mxgetn(prhs[0]); if (!mxisdouble(prhs[0]) mxiscomplex(prhs[0])!(mrows == 1 && ncols == 1)) mexerrmsgtxt("input must be a noncomplex scalar double."); } /* Create matrix for the return argument. */ plhs[0] = mxcreatedoublematrix(mrows,ncols, mxreal); /* Assign pointers to each input and output. */ x = mxgetpr(prhs[0]); y = 11/9/2014 mxgetpr(plhs[0]); /* Call the timestwo subroutine. */ timestwo(y,x); } 78 30

An additional examples #include "mex.h void timestwo_alt(double *y, double x) *y = 2.0*x; } void mexfunction(int nlhs, mxarray *plhs[], int nrhs, const mxarray *prhs[]) double *y; double x; /* Create a 1-by-1 matrix for the return argument. */ plhs[0] = mxcreatedoublematrix(1, 1, mxreal); /* Get the scalar value of the input x. */ /* Note: mxgetscalar returns a value, not a pointer. */ x = mxgetscalar(prhs[0]); /* Assign a pointer to the output. */ y = mxgetpr(plhs[0]); /* Call the timestwo_alt subroutine. */ timestwo_alt(y,x); } 11/9/2014 79 On-line help for mex file in MATLAB For on-line help support it need to create an m-file with the same name as mex-file. The function should be decelerated and help body should be written, but no function body. The file should be saved as m file with same name as function. % timestwo.m function [out1,out2] = timestwo(in1,in2) % timestwo takes 2 arguments and returns 2 11/9/2014 80 31

11/9/2014 Simple GUI examples http://webee.technion.ac.il/control/info/projects/students/2010/mi chal%20yemini%20and%20moria%20drukman/www/matla B%20GUI%20Tutorial%20-%20For%20Beginners.htm http://www.mathworks.com/videos/creating-a-gui-with-guide- 68979.html 11/9/2014 82 MATLAB GUI http://webee.technion.ac.il/control/info/proj ects/students/2010/michal%20yemini%20a nd%20moria%20drukman/www/matl AB%20GUI%20Tutorial%20- %20For%20Beginners.htm http://www.mathworks.com/videos/creating -a-gui-with-guide-68979.html 11/9/2014 83 32

Components of the System The Editor provides an interactive environment for you to create and edit C++ source code, editor also provides color cues to differentiate between various language elements The Compiler converts your source code into object code, and detects and reports errors in the compilation process; The object code output from the compiler is stored in files called object files. The object code usually have name with the extension.obj. The Linker The linker combines the various modules generated by the compiler from source code files, adds required code modules from program libraries supplied as part of C++, and welds everything into an executable whole. The Libraries 11/9/2014 85 11/9/2014 86 33

Editor window Solution Explorer window Output window 11/9/2014 87 11/9/2014 88 34

11/9/2014 89 11/9/2014 90 35

11/9/2014 91 Creating a project for a Win32 console application 11/9/2014 92 36

Creating a project for a Win32 console application 11/9/2014 93 Creating a project for a Win32 console application 11/9/2014 94 37

Class View Property Manager Resource View 11/9/2014 95 11/9/2014 96 38

11/9/2014 97 11/9/2014 98 39

11/9/2014 99 11/9/2014 100 40

11/9/2014 101 Executing the Program 11/9/2014 102 41

Creating an empty console project 11/9/2014 103 Creating an empty console project 11/9/2014 104 42

11/9/2014 105 11/9/2014 106 43

Creating an empty console project 11/9/2014 107 using namespace std; 11/9/2014 108 44

11/9/2014 109 11/9/2014 110 45

11/9/2014 111 11/9/2014 112 46

11/9/2014 113 Creating an empty console project 11/9/2014 114 47

11/9/2014 Win32 Debug מול Win32 Release ניתן לבנות את התוכנית עבור שני מטרות: Win32 Debug Target או עבור. Win32 Release Target קובץ ה- EXE בגרסת ה- Debug ימצא, לאחר הבניה, תחת המחיצה,DEBUG בעוד קובץ ה- EXE בגרסת ה- Release ימצא, לאחר הבניה, תחת המחיצה.RELEASE בגרסת ה- Release ניפוי השגיאות לא מאופשר ומתבצעת אופטימיזציה של המהירות, זאת בניגוד לגרסת ה-.Debug גרסת ב- Debug מיועדת לתהליך הפיתוח עצמו בעוד גרסת ה- Release מיועדת למסירה לידי המשתמש. נא להגיש תוכניות בגרסת ה- Release מכיוון שקל יותר להעבירם דרך הדואר האלקטרוני בגלל נפחם הקטן. לשם בחירה בגרבת ה- Release, יש להוסיף את סרגל הכלים המתאים על ידי: Tools Customize Toolbars Build 11/9/2014 115 http://www.ee.bgu.ac.il/~adcomplab/oop C++ tutorials 11/9/2014 116 48

11/9/2014 11/9/2014 117 Global Variables If you want more than one function to share a single copy of a variable, simply declare the variable as global in all the functions. The global declaration must occur before the variable is actually used in a function. Example: function h = falling(t) global GRAVITY h = 1/2*GRAVITY*t.^2; 49

Graphical User Interfaces GUIDE, the MATLAB Graphical User Interface Development Environment, provides a set of tools for creating graphical user interfaces (GUIs). These tools greatly simplify the process of designing and building GUIs. You can use the GUIDE tools to perform the following tasks: - Laying out the GUI. - Programming the GUI. Example template for a push button 50

The END 11/9/2014 121 51