Introduction to OOP. Contents:
|
|
- Gregory Ball
- 6 years ago
- Views:
Transcription
1 03/12/2016 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. 03/12/
2 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) 03/12/ Why C++? a b 03/12/
3 03/12/2016 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 03/12/ Inline function In the C and C++ programming languages, an inline function is one qualified with the keyword inline; this serves two purposes. Firstly, it serves as a compiler directive that suggests (but does not require) that the compiler substitute the body of the function inline by performing inline expansion, i.e. by inserting the function code at the address of each function call, thereby saving the overhead of a function call. In this respect it is analogous to the register storage class specifier, which similarly provides an optimization hint. The second purpose of inline is to change linkage behavior; the details of this are complicated. This is necessary due to the C/C++ separate compilation + linkage model, specifically because the definition (body) of the function must be duplicated in all translation units where it is used, to allow inlining during compiling, which, if the function has external linkage, causes a collision during linking (it violates uniqueness of external symbols; in C++, the One Definition Rule). C and C++ (and dialects such as GNU C and Visual C++) resolve this in different 03/12/2016 ways. 13 3
4 Inline function An inline function can be written in C++ like this: inline void swap(int & m, int & n) int temp = m; m = n; n = temp; Then, a statement such as the following: swap(x, y); will be translated into int temp = x; x = y; y = temp; 03/12/ Introduction to OOP We perceive the world around us as collection of objects, for example: a bird, a dog, a flower, a car, a house, a man and so on. Each object has properties. For example: size, shape, color, weight and so on. Each object has some operations (methods, functions) that characterize it. For example, an object, a person, may to move, talk, eat, etc., object car can move, twitter, light the way and so on. We learn about objects while viewing the properties and actions they can perform. 03/12/
5 03/12/2016 Introduction to OOP 03/12/ תכנות מונחה עצמים Progamming( )OOP,Object Oriented הוא תכנות הפועל בצורה דומה לזו שבה פועל מוח האדם הוא ממדל את "העולם" בעזרת עצמים. ניתן לרכז )לכמס, )encapsulate את כל המאפיינים והפונקציות השייכים לעצם מסויים למחלקה )class( על שמו. היחס בין עצם )object( ומחלקה )class( הוא היחס בין עוגה לתבנית עוגה. עצמים שונים יכולים להיות בעלי מאפיינים משותפים ו/או פעולות משותפות. למשל גם העצם אדם וגם העצם מכונית יכולים לנוע )למרות זאת תנועת האדם שונה מתנועת המכונית(. ניתן להגדיר מבנה היררכי של עצמים, עצמים כלליים יותר יהיו "האבות" של עצמים כלליים פחות ויוכלו לתת )להוריש, )inherit להם חלק מתכונותיהם. למשל העצם תוכי יכול לקבל מאפיינים מהעצם ציפור שכן תוכי הוא סוג של ציפור. The major properties of OOP ריכוזיות - Encapsulation / הסתרת מידע hiding Information ההכלה מחלקתית של כל המשאבים )קוד ונתונים( הדרושים לשם תיפקודו של העצם. עצמים אחרים יכולים רק להגיע לממשק, אותו העצם רוצה לפרסם כלפיהם, אך אין להם יכולת לדעת איך דברים נעשים בצורה פנימית. למשל העצם אדם יכול להשתמש בפעולת התנועה )נסיעה( של העצם המכונית )כלומר האדם יכול לנסוע במכונית( בלי להבין איך פועל המנוע בעצם זה. תורשה - Inheritance העברה של משאבים ממחלקה אחת למחלקה הנגזרת ממנה. בצורה זו אין צורך לחזור כמה פעמים על תכונות שמשותפות למחלקת היס ולמחלקה הנגזרת. למשל: המחלקה שולחן נגזרת מהמחלקה רהיט. ריבוי צורתיות - Polymorphism היכולת להקנות משמעויות שונות עבור פעולות עם שם זהה המתבצעות עבור עצמים שונים. למשל: פעולת "פתיחה" מקבלת משמעות שונה אם העצם המדובר הוא דלת או שהעצם המדובר הוא קופסת שימורים. 03/12/
6 Example 1: The class definition and the advantages of Encapsulation מחלקה )class( היא התבנית של העצם והיא יכולה להכיל מאפיינים ופונקציות של העצם. המשתנים והפונקציות יכולים לקבל אחת משלוש הרשאות: Public יש נגישות לפונקציות ולמשתנים אלו גם מתוך וגם מחוץ לעצם. Private יש נגישות לפונקציות ולמשתנים אלו רק מתוך העצם, אך לא מחוצה לו, אלא רק לעצמים שמוגדרים כעמיתים.)friends( Protected השראת ביניים. יש נגישות מתוך העצם ומתוך העמיתים שלו כמו כן יש נגישות מתוך נגזרותיו של העצם והעמיתים שלהם. 03/12/ Example 1: The class definition and the advantages of Encapsulation Constructor is class s function that is called automatically when creating the object. Typically use this function to initialize the instance variables. Constructor function has the same name as the name of the class. Destructor is class s function that is called automatically when object should be destroyed (Destructor occurs, for example, at the end of the program). Destructor function with the same name as the name of the class, but has a ~ character before the name. 03/12/
7 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 ) 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; 03/12/
8 03/12/2016 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)) struct _Complex complex; Complex.re = 3; Complex.im = 4; M = magnitude(complex); Complex.re = 5; 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 1 // Time class. 2 #include <iostream> 3 #include <iomanip> 4 using namespace std; // 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 private: 17 int hour; // 0-23 (24-hour clock format) 18 int minute; // int second; // ; // end class Time נתונים ופונקציות בעלי הרשאה ציבורית נתונים ופונקציות בעלי הרשאה פרטית הגדרת ה- class Time 8
9 23 // Time constructor initializes each data member to zero and פונקציית פונקציית הבונה state מאתחלת נתון // ensures all Time objects start in a consistent Time::Time() בנאי בעל הרשאה פרטית )private( ל 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 ) 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 // print Time 40 void Time::printTime() cout << setfill( '0' ) << setw( 2 ) << hour << ":" 43 << setw( 2 ) << minute << ":" << setw( 2 ) << second; 44 // end function printtime הזמן פונקצייה להדפסת הזמן נתונים בעלי הרשאה פרטית )private( 45 int main() 46 הצהרה על המשתנה t להיות אובייקט מטיפוס ה- class הנקרא Time 47 Time t; // instantiate object t of class Time // 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 כדי להדפיס את הזמן // 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 9
10 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. 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 = ; 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; 10
11 Operator Overloading C++ already has a number of types (e.g., int, float, char, etc.) that each have a number of built in operators. For example, a float can be added to another float and stored in yet another float with use of the + and = operators: floatc = floata + floatb; In this statement, floatb is passed to floata by way of the + operator. The + operator from floata then generates another float that is passed to floatc via the = operator. That new float is then stored in floatc by some method outlined in the = function. Lect 28 P. 30 Winter Quarter Operator Overloading (cont.) Operator overloading means that the operators: Have multiple definitions that are distinguished by the types of their parameters When the operator is used, the C++ compiler uses the types of the operands to determine which definition should be used. Lect 28 P. 31 Winter Quarter 11
12 Operator Overloading (cont.) class Complex private: double re, im; pablic; Complex() void Set(double r, double i) re = r; im = i; Complex operator -(Complex z) // Overloading '-' Type of value returned by the operator Complex tmp; tmp.re = re - z.re; tmp.im = im - z.im; return tmp; Class constructor Operator s new type definition New types of parameters (operands) the operator is to receive Operator Overloading (cont.) Steps for defining an overloaded operator: 1. Name the operator being overloaded. 2. Specify the (new) types of parameters (operands) the operator is to receive. 3. Specify the type of value returned by the operator. 4. Specify what action the operator is to perform. Lect 28 P. 34 Winter Quarter 12
13 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) 35 לעצם עיגול וגם לעצם קו. 03/12/2016 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 protected: 14 int x; // x part of coordinate pair 15 int y; // y part of coordinate pair 16 ; // end class Point #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. שלא הייתה קיימת בדוגמא הקודמת. 13
14 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 ) x = xvalue; // no need for validation 13 // end function setx 14 // return x from coordinate pair 15 int Point::getX() const return x; 18 // end function getx 19 // set y in coordinate pair 20 void Point::setY( int yvalue ) y = yvalue; // no need for validation 23 // end function sety 24 // return y from coordinate pair 25 int Point::getY() const return y; 28 // end function gety 29 // output Point2 object 30 void Point::print() const 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 private: 17 double radius; // Circle's radius ; // end class Circle 20 #endif Connection to the base בעלי הרשאה פרטית )private( 14
15 ו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 ) radius = ( radiusvalue < 0.0? 0.0 : radiusvalue ); 15 // end function setradius 16 // return radius 17 double Circle::getRadius() const return radius; 20 // end function getradius 21 // calculate and return area 22 double Circle::getArea() const return * radius * radius; 51 // end function getarea 25 // output Circle object 26 void Circle::print() const 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 שימוש בפונקציות שנורשו // display new point value מ- Point על מנת לשנות את 19 cout << "\n\nthe new location and radius of circle are\n"; הנתונים x ו- y 20 MyCircle.print(); )הם בהרשאת )protected // 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 << "\ny coordinate is " << MyCircle.getY() MyCircle.setX( 2 ); // set new x-coordinate << "\nradius is " << MyCircle.getRadius(); MyCircle.setY( 2 ); // set new y-coordinate Output after executing X coordinate is 37 Y coordinate is 43 Radius is 2.5 שימוש בפונקציה Print של MyCircle על מנת להדפיס את נתוני העיגול שימוש בפונקציה getarea של MyCircle על מנת להדפיס את נתוני העיגול The new location and radius of circle are Center = [2, 2]; Radius = 4.25 Area is
16 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 03/12/ 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. 03/12/
17 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. 03/12/ 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. 03/12/
18 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 03/12/ 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]; 03/12/
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 03/12/ 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. 03/12/ void swap (int *aptr, int *bptr) int temp = *aptr; *aptr = *bptr; *bptr = temp; void main() int x = 3, y = 4; swap(&x, &y); 19
20 Dynamic memory in C++ C++ מספקת לנו שני אופרטורים בזיכרון דינאמי: new - מאתר )תופס( זיכרון ומחזיר פוינטר להתחלה; ;new משחרר את הזיכרון שאותר מקודם ע"י - delete אופרטורים אלו משמשים לתפוס זיכרון ולשחרר זיכרון בזמן ריצה )פעולה (. למרות ש++ C תומכת בהקצאת זיכרון דינאמי גם ע''י בפונקציות ו- delete ; new להשתמש באופרטורים נהוג ו- free, malloc פונקציות malloc ו- free נכללות בגלל שפת C שהיא חלק משפת++ C. יתרונות של :new בצורה אוטומטית מאתר מספיק זיכרון בכדי להחזיק אובייקט מסוג ספציפי. לא צריך להשתמש באופרטור,sizeof מכוון שהגודל מותאם אוטומטית אוטומטית מחזיר פוינטר לאותו סוג ספציפי 03/12/ 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
21 Memory allocation for arrays ptr = new Array_Type[Size]; delete [ ] ptr; 1 #include <iostream.h> 2 #include <new.h> 3 int main ( ) 4 5 int *array, i; 6 // memory allocation for array of integers with length 10 7 array = new int [10]; 8 for ( i = 1; i < 10; i++) 9 10 *array++ = i; 11 cout << array[i] << "\n"; delete [] array; 14 return 0; 15 03/12/ Memory allocation for 2d array int** array = new int[sizey][sizex] Is It right? NOT Should be: int **array = new int*[sizey]; for(int i = 0; i < sizey; ++i) array[i] = new int[sizex]; and then clean up would be: for(int i = 0; i < sizey; ++i) delete [] array[i]; delete [] array; 03/12/
22 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; 03/12/ 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; 03/12/ x0065FDF4 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. 22
23 Polymorphic behavior of references 03/12/2016 #include <iostream> using namespace std; class A public: A() virtual void print() cout << "This is class A\n"; ; class B: public A public: B() virtual void print() cout << "This is class B\n"; ; int main() A a; A& ref2a = a; B b; A& ref2b = b; ref2a.print(); ref2b.print(); return 0; 56 Virtual Functions #include <iostream.h> #include <conio.h> class base public: virtual void show() cout <<"\n Base class show:"; void display() ; cout <<"\n Base class display:"; class drive: public base public: void show() cout <<"\n Drive class show:"; void display() cout <<"\n Drive class display:"; ; 03/12/
24 Virtual Functions void main() clrscr(); base obj1; base *p; cout <<"\n\t P points to base:\n"; p = &obj1; p -> display(); p -> show(); cout <<"\n\n\t P points to drive:\n"; drive obj2; p = &obj2; p -> display(); p -> show(); P points to Base Base class display Base class show P points to Drive Base class Display Drive class Show getch(); 03/12/ Virtual Functions Step 1: Start the program. Step 2: Declare the base class base. Step 3: Declare and define the virtual function show(). Step 4: Declare and define the function display(). Step 5: Create the derived class from the base class. Step 6: Declare and define the functions display() and show(). Step 7: Create the base class object and pointer variable. Step 8: Call the functions display() and show() using the base class object and pointer. Step 9: Create the derived class object and call the functions display() and show() using the derived class object and pointer. Step 10: Stop the program. 03/12/
25 Example3: Polymorphism Functions: 1. Breath 2. Speak Dog Pet Example Cat לפי תכונת הפולימופיזם, המצביע יכול ל- Class Base הרפרנס או כאשר שונות בדרכים להתנהג מרובה. בשימוש נמצא הוא לגשת למשל נוכל זו בצורה לפונקציה ב- class הנגזר במקום לפונקציה ב- class היס. ב-++ C הדבר נעשה תוך שימוש )מה וירטואליות בפונקציות של הפולימורפיות שיגדיר את העצם(. 03/12/ #include <iostream> 2 #include <string> 3 4 class Pet 5 6 public: 7 // Constructors, Destructors 8 Pet () 9 virtual ~Pet () // General methods 12 void breath(); 13 virtual void speak(); 14 ;// end class pet void Pet::breath() cout << Gasp" << endl; void Pet::speak() cout << "Growl" << endl; 24 הגדרת המחלקה "חיית מחמד" 1. פונקציות בנאי ופונקציית הורס וירטואלית 2. פונקציית נשימה 3. פונקציית דיבור וירטואלית פונקציית נשימה פונקציית דיבור Dog Pet Cat 25
26 "כלב" שיורשת 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; class Cat: public Pet "חתול" שיורשת 13 "חיית מחמד" 14 public: 15 Cat() void speak(); 18 ; 19 void Cat::speak() "חתול" המחליפה את cout << "Meow" << endl; void chorus(pet pet, Pet *petptr, Pet &petref) pet.speak(); petptr->speak(); petref.speak(); Dog 28 הגדרת המחלקה את המחלקה 1. פונקציות בנאי 2. פונקציית דיבור חדשה )פונקציית נשימה הורשה כבר( פונקציית דיבור חדשה למחלקה פונקציית הדיבור הישנה של ה- Class "חיית מחמד" הגדרת המחלקה את המחלקה 1. פונקציות בנאי 2. פונקציית דיבור חדשה )פונקציית נשימה הורשה כבר( פונקציית דיבור חדשה למחלקה Pet פונקציית הדיבור הישנה של המחלקה "חיית מחמד" הפונקציית "מקהלה" מקבלת את האובייקט Cat "חיית מחמד", מצביע אליו ורפרנס אליו קבלת רפרנס לעצם קבלת מצביע לעצם קבלת העצם אובייקט חדש יצירת מצביע למחלקת היס יצירת 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 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 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 26
27 03/12/2016 כאשר מעבירים ארגומנט 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 Friendship - Friend functions Private and protected members of a class cannot be accessed from outside the same class in which they are declared. However, this rule does not apply to "friends". Friends are functions or classes declared with the friend keyword. A non-member function can access the private and protected members of a class if it is declared a friend of that class. That is done by including a declaration of this external function within the class, and preceding it with the keyword friend. 03/12/
28 // friend functions #include <iostream> using namespace std; class Rectangle int width, height; public: Rectangle() Rectangle (int x, int y) : width(x), height(y) int area() return width * height; friend Rectangle duplicate (const Rectangle&); ; 24 Rectangle duplicate (const Rectangle& param) Rectangle res; res.width = param.width*2; res.height = param.height*2; return res; int main () Rectangle foo; Rectangle bar (2,3); foo = duplicate (bar); cout << foo.area() << '\n'; return 0; 03/12/ The duplicate function is a friend of class Rectangle. Therefore, function duplicate is able to access the members width and height (which are private) of different objects of type Rectangle. Notice though that neither in the declaration of duplicate nor in its later use in main, function duplicate is considered a member of class Rectangle. It isn't! It simply has access to its private and protected members without being a member. Typical use cases of friend functions are operations that are conducted between two different classes 03/12/2016 accessing private or protected members of both
29 Friend classes Similar to friend functions, a friend class is a class whose members have access to the private or protected members of another class: 03/12/ using namespace std; class Square; class Rectangle int width, height; public: int area () return (width * height); void convert (Square a); ; class Square friend class Rectangle; private: int side; public: Square (int a) : side(a) ; 16 void Rectangle::convert (Square a) width = a.side; height = a.side; int main () Rectangle rect; Square sqr (4); 03/12/ rect.convert(sqr); cout << rect.area(); 29
30 In this example, class Rectangle is a friend of class Square allowing Rectangle's member functions to access private and protected members of Square. More concretely, Rectangle accesses the member variable Square::side, which describes the side of the square. There is something else new in this example: at the beginning of the program, there is an empty declaration of class Square. This is necessary because class Rectangle uses Square (as a parameter in member convert), and Square uses Rectangle (declaring it a friend). Friendships are never corresponded unless specified: In our example, Rectangle is considered a friend class by Square, but Square is not considered a friend by Rectangle. Therefore, the member functions of Rectangle can access the protected and private members of Square but not the other way around. Of course, Square could also be declared friend of Rectangle, if needed, granting such an access. Another property of friendships is that they are not transitive: The friend of a friend is not considered a friend unless explicitly specified 03/12/ 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; 30
31 03/12/2016 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. 03/12/ 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. 03/12/
32 Components of a MEX-file A gateway routine, mexfunction, that interfaces C/C++ and MATLAB data A computational routine, called from the gateway routine. This routine performs the computations that the MEX-file should implement Preprocessor macros, for building platform independent code 03/12/ 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... */ 03/12/
33 03/12/2016 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 03/12/ The computational routine The computational routine is called from the gateway routine It is a good idea to place the computational routine in a separate subroutine although it can be included in the gateway routine 03/12/
34 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]); 03/12/ C compiler sec=win64 03/12/
35 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 03/12/ Compiler setup >> mex -setup 1) Welcome to mex -setup. This utility will help you set up a default compiler. For a list of supported compilers, see Please choose your compiler for building MEX-files: Would you like mex to locate installed compilers [y]/n? put option - y 03/12/
36 03/12/2016 Compiler setup-setup 2) Please choose your compiler for building MEX-files: Would you like mex to locate installed compilers [y]/n? y Select a compiler: [1] Microsoft Software Development Kit (SDK) 7.1 in C:\Program Files (x86)\microsoft Visual Studio 10.0 [2] Microsoft Visual C in C:\Program Files (x86)\microsoft Visual Studio 10.0 [0] None put option /12/ Compiler setup Please verify your choices: Compiler: Microsoft Software Development Kit (SDK) 7.1 Location: C:\Program Files (x86)\microsoft Visual Studio 10.0 Are these correct [y]/n? put option - y 03/12/
37 Working with mxarrays [a,b]=timestwo([ ; ], 8) /* timestwo.c */ #include "mex.h" void mexfunction(int nlhs, mxarray *plhs[], int nrhs, const mxarray *prhs[]) int i, j, m, n; double *data1, *data2; if (nrhs!= nlhs) mexerrmsgtxt("the number of input and output arguments must be the same."); for (i = 0; i < nrhs; i++) m = mxgetm(prhs[i]); /* Find the dimension of the data */ n = mxgetn(prhs[i]); /* Create an mxarray for the output */ plhs[i] = mxcreatedoublematrix(m, n, mxreal); data1 = mxgetpr(prhs[i]); /* Get the data passed in */ /* Create an array for the output's data */ data2 = (double *) mxmalloc(m*n *sizeof(double)); for (j = 0; j < m*n; j++) data2[j] = 2 * data1[j]; /* Put data in the array */ mxsetpr(plhs[i], data2); 03/12/ 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 03/12/
38 An additional examples #include "mex.h" void timestwo(double y[], double x[], int m, int n) int j; for (j = 0; j < m*n; j++) y[j] = 2.0 * x[j]; 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"); mrows = mxgetm(prhs[0]); ncols = mxgetn(prhs[0]); plhs[0] = mxcreatedoublematrix(mrows,ncols, mxreal); x = mxgetpr(prhs[0]); /* Assign pointers to each input and output. */ y = mxgetpr(plhs[0]); timestwo(y,x,mrows,ncols); /* Call the timestwo subroutine. */ 03/12/ 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 */ x = mxgetscalar(prhs[0]); /* Get the scalar value of the input x */ y = mxgetpr(plhs[0]); /* Assign a pointer to the output */ timestwo_alt(y,x); /* Call the timestwo_alt subroutine */ 03/12/
39 Working with two cpp files // timestwo.h must be in the current directory #ifndef EXTFUNC_H #define EXTFUNC_H void extfunc(double y[], double x[], int m, int n); #endif All CPP files should be added to compiled line For example: mex C:\Work\MEX\Test2\timestwo.cpp C:\Work\MEX\Test2\extFunc.cpp 03/12/ Working with two cpp files External function definition // extfunc.cpp file #include "extfunc.h" #include <iostream> #include <iomanip> using namespace std; void extfunc(double y[], double x[], int m, int n) int j; for (j = 0; j < m*n; j++) y[j] = 2.0 * x[j]; cout << "OK"; Operator cout print OK in MATLAB console and helps to debug MEX functions 03/12/
40 Working with two cpp files // timestwo.cpp file #include "mex.h" #include "extfunc.cpp" 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"); mrows = mxgetm(prhs[0]); ncols = mxgetn(prhs[0]); plhs[0] = mxcreatedoublematrix(mrows,ncols, mxreal); x = mxgetpr(prhs[0]); /* Assign pointers to each input and output. */ y = mxgetpr(plhs[0]); extfunc(y,x,mrows,ncols); /* Call the timestwo subroutine. */ 03/12/ /12/
41 Simple GUI examples %20Yemini%20and%20Moria%20Drukman/WWW/MATLAB%20G UI%20Tutorial%20-%20For%20Beginners.htm html 03/12/ /12/
42 C++ tutorials 03/12/ /12/
43 The END 03/12/
Introduction to OOP. Contents:
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;
More informationIS 0020 Program Design and Software Tools
1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Operator Overloading, Inheritance Lecture 6 February 10, 2005 Fundamentals of Operator Overloading 2 Use operators with objects
More informationShort Notes of CS201
#includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system
More informationCS201 - Introduction to Programming Glossary By
CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with
More informationתכנות מונחה עצמים משחקים תשע"ו
move semantics 1 תכנות מונחה עצמים ופיתוח משחקים תשע"ו סמנטיקת ההעברה semantics( )Move move semantics 2 מטרה האצה של התוכניות, שיפור בביצועים על ידי חסכון בבנייה והעתקה של אובייקטים זמניים move semantics
More informationPOINTERS - Pointer is a variable that holds a memory address of another variable of same type. - It supports dynamic allocation routines. - It can improve the efficiency of certain routines. C++ Memory
More informationCS3157: Advanced Programming. Outline
CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching
More informationChapter 20 - C++ Virtual Functions and Polymorphism
Chapter 20 - C++ Virtual Functions and Polymorphism Outline 20.1 Introduction 20.2 Type Fields and switch Statements 20.3 Virtual Functions 20.4 Abstract Base Classes and Concrete Classes 20.5 Polymorphism
More information2015 Academic Challenge
2015 Academic Challenge COMPUTER SCIENCE TEST - STATE This Test Consists of 30 Questions Computer Science Test Production Team James D. Feher, McKendree University Author/Team Leader Nathan White, McKendree
More informationFast Introduction to Object Oriented Programming and C++
Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming
More informationNote 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...
CISC 2000 Computer Science II Fall, 2014 Note 12/1/2014 1 Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance... (a) What s the purpose of inheritance?
More informationAN OVERVIEW OF C++ 1
AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function
More informationCOMP322 - Introduction to C++
COMP322 - Introduction to C++ Winter 2011 Lecture 05 - I/O using the standard library & Introduction to Classes Milena Scaccia School of Computer Science McGill University February 1, 2011 Final note on
More informationA brief introduction to C++
A brief introduction to C++ Rupert Nash r.nash@epcc.ed.ac.uk 13 June 2018 1 References Bjarne Stroustrup, Programming: Principles and Practice Using C++ (2nd Ed.). Assumes very little but it s long Bjarne
More informationתוכנה 1. תרגול מספר 11: Static vs. Dynamic Binding מחלקות מקוננות Nested Classes
תוכנה 1 תרגול מספר 11: Static vs. Dynamic Binding מחלקות מקוננות Nested Classes class Outer { static class NestedButNotInner {... class Inner {... מחלקות מקוננות NESTED CLASSES 2 מחלקה מקוננת Class) )Nested
More informationלתיכנות עם MATLAB Lecture 5: Boolean logic and Boolean expressions
מבוא לתיכנות עם MATLAB 234127 Lecture 5: Boolean logic and Boolean expressions Written by Prof. Reuven Bar-Yehuda, Technion 2013 Based on slides of Dr. Eran Eden, Weizmann 2008 1 >>g = [89 91 80 98]; >>p
More informationCS304 Object Oriented Programming Final Term
1. Which of the following is the way to extract common behaviour and attributes from the given classes and make a separate class of those common behaviours and attributes? Generalization (pg 29) Sub-typing
More informationBasic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces
Basic memory model Using functions Writing functions Basics Prototypes Parameters Return types Functions and memory Names and namespaces When a program runs it requires main memory (RAM) space for Program
More informationQuiz Start Time: 09:34 PM Time Left 82 sec(s)
Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability
More informationCS201 Latest Solved MCQs
Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability
More informationC++ Memory Map. A pointer is a variable that holds a memory address, usually the location of another variable in memory.
Pointer C++ Memory Map Once a program is compiled, C++ creates four logically distinct regions of memory: Code Area : Area to hold the compiled program code Data Area : Area to hold global variables Stack
More informationלתיכנות עם MATLAB Lecture 5: Boolean logic and Boolean expressions
מבוא לתיכנות עם MATLAB 23427 Lecture 5: Boolean logic and Boolean expressions Written by Prof. Reuven Bar-Yehuda, Technion 203 Based on slides of Dr. Eran Eden, Weizmann 2008 ביטויים לוגיים דוגמא: תקינות
More informationOperator overloading
1 Introduction 2 The copy constructor 3 Operator Overloading 4 Eg 1: Adding two vectors 5 The -> operator 6 The this pointer 7 Overloading = 8 Unary operators 9 Overloading for the matrix class 10 The
More informationChapter 19 C++ Inheritance
Chapter 19 C++ Inheritance Angela Chih-Wei i Tang Department of Communication Engineering National Central University JhongLi, Taiwan 2009 Fall Outline 19.11 Introduction ti 19.2 Inheritance: Base Classes
More informationPointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation The new operator The delete operator Dynamic Memory Allocation for Arrays 1 C++ Data Types simple
More informationCS201 Some Important Definitions
CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data
More informationChapter 19 - C++ Inheritance
Chapter 19 - C++ Inheritance 19.1 Introduction 19.2 Inheritance: Base Classes and Derived Classes 19.3 Protected Members 19.4 Casting Base-Class Pointers to Derived-Class Pointers 19.5 Using Member Functions
More informationChapter 1: Object-Oriented Programming Using C++
Chapter 1: Object-Oriented Programming Using C++ Objectives Looking ahead in this chapter, we ll consider: Abstract Data Types Encapsulation Inheritance Pointers Polymorphism Data Structures and Algorithms
More informationIntroduction to C++ Systems Programming
Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions
More informationIntroduction to Programming session 24
Introduction to Programming session 24 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2010 These slides are created using Deitel sslides Sharif Universityof Technology Outlines Introduction
More informationInheritance (Deitel chapter 9)
Inheritance (Deitel chapter 9) 1 2 Plan Introduction Superclasses and Subclasses protected Members Constructors and Finalizers in Subclasses Software Engineering with Inheritance 3 Introduction Inheritance
More informationתוכנה 1 סמסטר א' תשע"א
General Tips on Programming תוכנה 1 סמסטר א' תשע"א תרגול מס' 6 מנשקים, דיאגרמות וביטים * רובי בוים ומתי שמרת Write your code modularly top-down approach Compile + test functionality on the fly Start with
More informationCS201- Introduction to Programming Current Quizzes
CS201- Introduction to Programming Current Quizzes Q.1 char name [] = Hello World ; In the above statement, a memory of characters will be allocated 13 11 12 (Ans) Q.2 A function is a block of statements
More informationIntroducing C++ to Java Programmers
Introducing C++ to Java Programmers by Kip Irvine updated 2/27/2003 1 Philosophy of C++ Bjarne Stroustrup invented C++ in the early 1980's at Bell Laboratories First called "C with classes" Design Goals:
More informationLecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology
Lecture 8: Object-Oriented Programming (OOP) 1 Introduction to C++ 2 Overview Additional features compared to C: Object-oriented programming (OOP) Generic programming (template) Many other small changes
More informationCome and join us at WebLyceum
Come and join us at WebLyceum For Past Papers, Quiz, Assignments, GDBs, Video Lectures etc Go to http://www.weblyceum.com and click Register In Case of any Problem Contact Administrators Rana Muhammad
More informationProgramming, numerics and optimization
Programming, numerics and optimization Lecture A-4: Object-oriented programming Łukasz Jankowski ljank@ippt.pan.pl Institute of Fundamental Technological Research Room 4.32, Phone +22.8261281 ext. 428
More informationChapter 15 - C++ As A "Better C"
Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference
More informationSRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR
SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR 603203 DEPARTMENT OF COMPUTER SCIENCE & APPLICATIONS QUESTION BANK (2017-2018) Course / Branch : M.Sc CST Semester / Year : EVEN / II Subject Name
More informationChapter 9 - Object-Oriented Programming: Inheritance
Chapter 9 - Object-Oriented Programming: Inheritance 9.1 Introduction 9.2 Superclasses and Subclasses 9.3 protected Members 9.4 Relationship between Superclasses and Subclasses 9.5 Case Study: Three-Level
More informationthe gamedesigninitiative at cornell university Lecture 7 C++ Overview
Lecture 7 Lecture 7 So You Think You Know C++ Most of you are experienced Java programmers Both in 2110 and several upper-level courses If you saw C++, was likely in a systems course Java was based on
More informationIntroduction Of Classes ( OOPS )
Introduction Of Classes ( OOPS ) Classes (I) A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions. An object is an instantiation of a class.
More informationCSCI 171 Chapter Outlines
Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures
More informationFunction Overloading
Function Overloading C++ supports writing more than one function with the same name but different argument lists How does the compiler know which one the programmer is calling? They have different signatures
More informationMidterm Review. PIC 10B Spring 2018
Midterm Review PIC 10B Spring 2018 Q1 What is size t and when should it be used? A1 size t is an unsigned integer type used for indexing containers and holding the size of a container. It is guarenteed
More informationUSING LAPACK SOLVERS FOR STRUCTURED MATRICES WITHIN MATLAB
USING LAPACK SOLVERS FOR STRUCTURED MATRICES WITHIN MATLAB Radek Frízel*, Martin Hromčík**, Zdeněk Hurák***, Michael Šebek*** *Department of Control Engineering, Faculty of Electrical Engineering, Czech
More informationCS250 Intro to CS II. Spring CS250 - Intro to CS II 1
CS250 Intro to CS II Spring 2017 CS250 - Intro to CS II 1 Topics Virtual Functions Pure Virtual Functions Abstract Classes Concrete Classes Binding Time, Static Binding, Dynamic Binding Overriding vs Redefining
More informationFor Teacher's Use Only Q No Total Q No Q No
Student Info Student ID: Center: Exam Date: FINALTERM EXAMINATION Spring 2010 CS201- Introduction to Programming Time: 90 min Marks: 58 For Teacher's Use Only Q No. 1 2 3 4 5 6 7 8 Total Marks Q No. 9
More informationPolymorphism Part 1 1
Polymorphism Part 1 1 What is Polymorphism? Polymorphism refers to a programming language s ability to process objects differently depending on their data type or class. Number person real complex kid
More informationCS250 Final Review Questions
CS250 Final Review Questions The following is a list of review questions that you can use to study for the final. I would first make sure that you review all previous exams and make sure you fully understand
More informationClasses: A Deeper Look
Classes: A Deeper Look 1 Introduction Implementing a Time Abstract Data Type with a class Class Scope and Accessing Class Members Separating Interface from Implementation Controlling Access to Members
More informationPointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.
Pointers and Arrays CS 201 This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book. Pointers Powerful but difficult to master Used to simulate pass-by-reference
More informationמבוא למדעי המחשב תרגול 8 רשימה משורשרת כללית, Comparator
מבוא למדעי המחשב 2017 תרגול 8 רשימה משורשרת כללית, Comparator בתרגול היום. LinkedList בניית ההכללה מ- LinkIntList תרגול המבנה ושימושיו ממשקים: Comparator Sorted Linked List ל- LinkedList ע"י שימוש ב- Comparator
More informationMore C++ : Vectors, Classes, Inheritance, Templates
Vectors More C++ : Vectors,, Inheritance, Templates vectors in C++ basically arrays with enhancements indexed similarly contiguous memory some changes defined differently can be resized without explicit
More informationReference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that
Reference Parameters There are two ways to pass arguments to functions: pass-by-value and pass-by-reference. pass-by-value A copy of the argument s value is made and passed to the called function. Changes
More information1. Which of the following best describes the situation after Line 1 has been executed?
Instructions: Submit your answers to these questions to the Curator as OQ3 by the posted due date and time. No late submissions will be accepted. For the next three questions, consider the following short
More informationC++ 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++ 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++ Rulez! C++ Mini-Course Part 1: Mechanics C++ is a
More informationOutline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor
Outline EDAF50 C++ Programming 4. Classes Sven Gestegård Robertz Computer Science, LTH 2018 1 Classes the pointer this const for objects and members Copying objects friend inline 4. Classes 2/1 User-dened
More informationSFU CMPT Topic: Classes
SFU CMPT-212 2008-1 1 Topic: Classes SFU CMPT-212 2008-1 Topic: Classes Ján Maňuch E-mail: jmanuch@sfu.ca Friday 15 th February, 2008 SFU CMPT-212 2008-1 2 Topic: Classes Encapsulation Using global variables
More informationMore C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com
More C++ : Vectors, Classes, Inheritance, Templates with content from cplusplus.com, codeguru.com 2 Vectors vectors in C++ basically arrays with enhancements indexed similarly contiguous memory some changes
More informationObject-Oriented Programming
Object-Oriented Programming Section 3: Classes and inheritance (1) Piotr Mielecki, Ph. D. piotr.mielecki@pwr.edu.pl pmielecki@gmail.com Class vs. structure declaration Inheritance and access specifiers
More informationWhere do we stand on inheritance?
In C++: Where do we stand on inheritance? Classes can be derived from other classes Basic Info about inheritance: To declare a derived class: class :public
More informationPreview 9/20/2017. Object Oriented Programing with C++ Object Oriented Programing with C++ Object Oriented Programing with C++
Preview Object Oriented Programming with C++ Class Members Inline Functions vs. Regular Functions Constructors & Destructors Initializing class Objects with Constructors C++ Programming Language C Programming
More informationSTUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING
OBJECT ORIENTED PROGRAMMING STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING 1. Object Oriented Programming Paradigms 2. Comparison of Programming Paradigms 3. Basic Object Oriented Programming
More informationObject-Oriented Programming for Scientific Computing
Object-Oriented Programming for Scientific Computing Dynamic Memory Management Ole Klein Interdisciplinary Center for Scientific Computing Heidelberg University ole.klein@iwr.uni-heidelberg.de 2. Mai 2017
More informationClasses: Member functions // classes example #include <iostream> using namespace std; Objects : Reminder. Member functions: Methods.
Classes: Methods, Constructors, Destructors and Assignment For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Piyush Kumar Classes: Member functions // classes
More informationHow to get Real Time Data into Matlab
How to get Real Time Data into Matlab First make sure you have Visual Studio 6.0 installed. You re going to have to build a mex file in visual studio. A mex file is just C code that has been compiled to
More informationMiri Ben-Nissan (Kopel) (2017)
Miri Ben-Nissan (Kopel) (2017) int attributes set of operations Attributes: 4 bytes. Integer numbers. Operations: numerical operators logical operations bit operations I/O operations Data Types define
More informationInheritance, and Polymorphism.
Inheritance and Polymorphism by Yukong Zhang Object-oriented programming languages are the most widely used modern programming languages. They model programming based on objects which are very close to
More informationOBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe
OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++
More informationOBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak
OBJECT ORIENTED PROGRAMMING Ms. Ajeta Nandal C.R.Polytechnic,Rohtak OBJECT ORIENTED PARADIGM Object 2 Object 1 Data Data Function Function Object 3 Data Function 2 WHAT IS A MODEL? A model is an abstraction
More informationAbstract Data Types (ADT) and C++ Classes
Abstract Data Types (ADT) and C++ Classes 1-15-2013 Abstract Data Types (ADT) & UML C++ Class definition & implementation constructors, accessors & modifiers overloading operators friend functions HW#1
More informationModule 7 b. -Namespaces -Exceptions handling
Module 7 b -Namespaces -Exceptions handling C++ Namespace Often, a solution to a problem will have groups of related classes and other declarations, such as functions, types, and constants. C++provides
More informationObject Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year
Object Oriented Programming Assistant Lecture Omar Al Khayat 2 nd Year Syllabus Overview of C++ Program Principles of object oriented programming including classes Introduction to Object-Oriented Paradigm:Structures
More informationConstructor - example
Constructors A constructor is a special member function whose task is to initialize the objects of its class. It is special because its name is same as the class name. The constructor is invoked whenever
More informationObject Oriented Pragramming (22316)
Chapter 1 Principles of Object Oriented Programming (14 Marks) Q1. Give Characteristics of object oriented programming? Or Give features of object oriented programming? Ans: 1. Emphasis (focus) is on data
More informationCOMP322 - Introduction to C++ Lecture 02 - Basics of C++
COMP322 - Introduction to C++ Lecture 02 - Basics of C++ School of Computer Science 16 January 2012 C++ basics - Arithmetic operators Where possible, C++ will automatically convert among the basic types.
More informationObject-Oriented Programming Concepts
Object-Oriented Programming Concepts Object-oriented programming מונחה עצמים) (תכנות involves programming using objects An object ) represents (עצם an entity in the real world that can be distinctly identified
More informationIntroduction to the C programming language
Introduction to the C programming language From C to C++: Stack and Queue Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 23, 2010 Outline 1 From struct to classes
More informationLecture 14: more class, C++ streams
CIS 330: / / / / (_) / / / / _/_/ / / / / / \/ / /_/ / `/ \/ / / / _/_// / / / / /_ / /_/ / / / / /> < / /_/ / / / / /_/ / / / /_/ / / / / / \ /_/ /_/_/_/ _ \,_/_/ /_/\,_/ \ /_/ \ //_/ /_/ Lecture 14:
More informationJayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT
CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT Two Mark Questions UNIT - I 1. DEFINE ENCAPSULATION. Encapsulation is the process of combining data and functions
More informationIntroduction to the C programming language
Introduction to the C programming language From C to C++: Stack and Queue Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 23, 2010 Outline 1 From struct to classes
More informationObject-Oriented Programming
- oriented - iuliana@cs.ubbcluj.ro Babes-Bolyai University 2018 1 / 56 Overview - oriented 1 2 -oriented 3 4 5 6 7 8 Static and friend elements 9 Summary 2 / 56 I - oriented was initially created by Bjarne
More informationCAMBRIDGE SCHOOL, NOIDA ASSIGNMENT 1, TOPIC: C++ PROGRAMMING CLASS VIII, COMPUTER SCIENCE
CAMBRIDGE SCHOOL, NOIDA ASSIGNMENT 1, TOPIC: C++ PROGRAMMING CLASS VIII, COMPUTER SCIENCE a) Mention any 4 characteristic of the object car. Ans name, colour, model number, engine state, power b) What
More informationC++_ MARKS 40 MIN
C++_16.9.2018 40 MARKS 40 MIN https://tinyurl.com/ya62ayzs 1) Declaration of a pointer more than once may cause A. Error B. Abort C. Trap D. Null 2Whice is not a correct variable type in C++? A. float
More informationהקלחמ ה תמרב ת ונ וכ ת (static members ) יליזרב דהוא Java תפשב ם דקת מ תונכת ביבא ל ת תטיסרבינוא
ת כו נו ת ברמת ה מחלקה (static members) אוהד ברזילי תכנות מ תקד ם בשפת Java אוניברסיטת ת ל אביב static keyword שדות המוגדרים כ static מציינים כי הם מוגדרים ברמת המחלקה ולא ברמת עצם כל העצמים של אותה מחלקה
More informationdouble d0, d1, d2, d3; double * dp = new double[4]; double da[4];
All multiple choice questions are equally weighted. You can generally assume that code shown in the questions is intended to be syntactically correct, unless something in the question or one of the answers
More informationCS11 Intro C++ Spring 2018 Lecture 1
CS11 Intro C++ Spring 2018 Lecture 1 Welcome to CS11 Intro C++! An introduction to the C++ programming language and tools Prerequisites: CS11 C track, or equivalent experience with a curly-brace language,
More informationCS24 Week 3 Lecture 1
CS24 Week 3 Lecture 1 Kyle Dewey Overview Some minor C++ points ADT Review Object-oriented Programming C++ Classes Constructors Destructors More minor Points (if time) Key Minor Points const Motivation
More informationCS11 Introduction to C++ Fall Lecture 1
CS11 Introduction to C++ Fall 2006-2007 Lecture 1 Welcome! 8 Lectures (~1 hour) Slides posted on CS11 website http://www.cs.caltech.edu/courses/cs11 7 Lab Assignments on course website Available on Monday
More informationUNIVERSITI TEKNIKAL MALAYSIA MELAKA FACULTY INFORMATION TECHNOLOGY AND COMMUNICATION (FTMK) BITE 1513 GAME PROGRAMMING I.
y UNIVERSITI TEKNIKAL MALAYSIA MELAKA FACULTY INFORMATION TECHNOLOGY AND COMMUNICATION (FTMK) BITE 1513 GAME PROGRAMMING I Lab Module 7 CLASSES, INHERITANCE AND POLYMORPHISM Department of Media Interactive
More information3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.
3.Constructors and Destructors Develop cpp program to implement constructor and destructor. Constructors A constructor is a special member function whose task is to initialize the objects of its class.
More informationC++ 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++ 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++ Rulez! C++ Mini-Course Part 1: Mechanics C++ is a
More informationJAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)
Estd: 1994 JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli - 621014 (An approved by AICTE and Affiliated to Anna University) ISO 9001:2000 Certified Subject Code & Name : CS 1202
More informationOOP THROUGH C++(R16) int *x; float *f; char *c;
What is pointer and how to declare it? Write the features of pointers? A pointer is a memory variable that stores the address of another variable. Pointer can have any name that is legal for other variables,
More informationpointers & references
pointers & references 1-22-2013 Inline Functions References & Pointers Arrays & Vectors HW#1 posted due: today Quiz Thursday, 1/24 // point.h #ifndef POINT_H_ #define POINT_H_ #include using
More informationOperating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst
Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst Department of Computer Science Why C? Low-level Direct access to memory WYSIWYG (more or less) Effectively
More informationInstantiation of Template class
Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double
More informationADTs & Classes. An introduction
ADTs & Classes An introduction Quick review of OOP Object: combination of: data structures (describe object attributes) functions (describe object behaviors) Class: C++ mechanism used to represent an object
More informationCpt S 122 Data Structures. Introduction to C++ Part II
Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function
More information