Presentation is loading. Please wait.

Presentation is loading. Please wait.

Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008.

Similar presentations


Presentation on theme: "Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008."— Presentation transcript:

1 Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

2 Course Requirements Goals To learn basics of Object Oriented Programming To program in C++ Practically see Design Paradigms Exercises Exercises will be 20% of the final grade Exam 80% of the final grade

3 Resources Books C++ Programming Language, by Bjarne Stroustrup Thinking in C++, by Bruce Eckel C++ Professional in Hebrew Design Patterns, by Gamma, Helm, Johnson, and Vlissidis Compilers Visual C++ Borland C++ GNU C++ (gcc)

4 Introduction to C++

5 History C++ is written by Bjarne Stroustrup from AT&T Bell Laboratories C++ is the extension into ANSI-C Procedural Programming  Object Oriented Programming It supports Object Oriented Programming Generic Programming etc.

6 History 1980C with classes 1983Name C++ is given 1985Version 1.0 (Basics) 1987Standardization Process 1989ANSI C++ 1989Version 2.0 (Multi-inheritance, Operator Overloading) 1991Version 3.0 (Templates) 1995Standard Template Library (STL), namespace, RTTI C++ Design has been influenced from languages Simula67, Algol68, and SmallTalk.

7 Introduction to C++ Advantageous Largely used Extension to C Object Oriented Programming Standard Template Library Efficient Programs can be written Disadvantageous Complicated Language No support for Concurrent Programming No support for Serialization

8 Program Execution Language Translation The translation of Human-Understandable Code into Machine- Understandable Two types of Translation 1. Interpreter 2. Compiler C++ Compilation Process 1. Preprocessor Optionally also does Global Optimizations 2. Compiler 1. First Pass: Creates parse tree 2. Second Pass: Creates object modules (*.obj) Optionally also does Peephole Optimizations 3. Linker From a list of Object Files creates an executable

9 Declaration vs. Definition Declaration and Definition in C++ Declaration: Introduces a name to the compiler. This name might be a user defined type, a variable, or a function. Definition: It says make this function/variable here. It allocates storage for the name. For any name many declarations can be done, but exactly one definition must exist.

10 Declaration vs. Definition Functions Definition int func1(char, float) { /*…the code…*/ } Declaration int func1(char, float); Variables Definition int a ; Declaration extern int a ;

11 Declaration vs. Definition // File: Exemple1.cpp extern int i; // Declaration without definition extern float f(float); // Function declaration float b; // Declaration & definition float float f(float a) { // Definition return a + 1.0; } int i; // Definition int h(int x) { // Declaration & definition return x + 1; } int main() { b = 1.0; i = 2; f(b); h(i); }

12 Header Files A header file is a file containing the external declarations for a library. It conventionally has a file name *.h. To include a header file, use the #include preprocessor directive. Search the file in “implementation-defined way.” #include “local.h” Search the file in “include search path” #include Old style vs. New Style Libraries #include #include #include #include

13 Using Libraries For using libraries 1. Include the library’s header file. 2. Use the functions and variables in the library. 3. Link the library into the executable program.

14 First C++ Program – Hello.cpp // Hello.cpp #include //Stream declarations using namespace std; int main() { cout << "Hello, World! I am " << 8 << " Today!" << endl; } // To Compile: gcc Hello.cpp // org++ Hello.cpp //orcl Hello.cpp

15 Some C++ Examples Number Conversion // Numconv.cpp // Converts decimal to octal and hex #include using namespace std; int main() { int number; cout > number; cout << "value in octal = 0" << oct << number << endl; cout << "value in hex = 0x" << hex << number << endl; }

16 Some C++ Examples string class // HelloStrings.cpp // The basics of the Standard C++ string class #include #include using namespace std; int main() { string s1, s2; // Empty strings string s3 = "Hello, World."; // Initialized string s4("I am"); // Also initialized s2 = "Today"; // Assigning to a string s1 = s3 + " " + s4; // Combining strings s1 += " 8 "; // Appending to a string cout << s1 + s2 + "!" << endl; }

17 Some C++ Examples File Input Output // Scopy.cpp // Copy one file to another, a line at a time #include #include using namespace std; int main() { ifstream in(“File1.txt"); // Open for reading ofstream out(“File2.txt"); // Open for writing string s; while(getline(in, s)) // Discards newline char out << s << "\n"; //... must add it back }

18 Some C++ Examples Fill String // FillString.cpp // Read an entire file into a single string #include #include #include using namespace std; int main() { ifstream in(“File.txt”); string s, line; while(getline(in, line)) s += line + "\n”; cout << s; }

19 Some C++ Examples vector class // Fillvector.cpp // Copy an entire file into a vector of string #include #include #include #include using namespace std; int main() { vector v; ifstream in("Fillvector.cpp"); string line; while(getline(in, line)) v.push_back(line); // Add the line to the end // Add line numbers: for(int i = 0; i < v.size(); i++) cout << i << ": " << v[i] << endl; }

20 Some C++ Examples vector with integers // Intvector.cpp // Creating a vector that holds integers #include #include using namespace std; int main() { vector v; for(int i = 0; i < 10; i++) v.push_back(i); for(int i = 0; i < v.size(); i++) cout << v[i] << ", "; cout << endl; for(int i = 0; i < v.size(); i++) v[i] = v[i] * 10; // Assignment for(int i = 0; i < v.size(); i++) cout << v[i] << ", "; cout << endl; }

21 Exercises 1. Using Numconv.cpp as guidelines, create a program that asks for the radius of a circle and prints the area of that circle. 2. Create a program that opens a file and counts the whitespace-separated words in that file. 3. Change Fillvector.cpp so that it prints the lines (backwards) from last to first. 4. Display a file a line at a time, waiting for the user to press the “Enter” key after each line. 5. Create a vector and put 25 floating-point numbers into it using a for loop. Display the vector. 6. Create three vector objects and fill the first two as in the previous exercise. Write a for loop that adds each corresponding element in the first two vectors and puts the result in the corresponding element of the third vector. Display all three vectors. 7. Create a vector and put 25 numbers into it as in the previous exercises. Now square each number and put the result back into the same location in the vector. Display the vector before and after the multiplication.

22 Types and Declarations

23 Consider x = y + f(2) ; To make it meaningful for C++ float x ;// x is a floating point variable int y = 7 ;// y is an integer variable // initialized to 7 float f(int) ;// f is a function taking argument // type integer and returning // floating point number

24 Fundamental Types Boolean Type bool Character Types such as char Integer Types such as int Floating-Point Types such as double Absence of Information Type void Enumeration Types enum Pointer Types int* Array Types char[] Reference Types double& Structures and Classes stru { … } class { … }

25 Booleans bool is either true or false. Examples: void f(int a, int b) { bool check = a==b ; // … } bool is_open(File*) ; bool greater(int a, int b) { return a>b ; } Implicit Conversions bool to int false  0true  1 int to bool 0  falseNon-zero  true

26 Character Types char holds a character of implementation’s character set Example:char ch = ‘a’ ; Two types signed char-127 … 127 unsigned char0 … 255 For Unicode wchar_t Character Literals ‘a’‘0’‘\n’‘\t’L’ab’

27 Integer Types Three forms int signed int( or signed ) unsigned int( or unsigned ) Three sizes short int( or short ) int long int( or long ) Integer Literals Decimal:063 Octal:00077 Hexadecimal:0x00x3f U for Unsigned Literals63U L for Long Literals63L

28 Floating Point Types Three Sizes float double long double Floating Point Literals 1.23.230.231. 1.01.2e101.23e-15 Suffix F for float3.1416f2.0F

29 Fundamental Types sizeof(…) gives the size of any type in terms of chars sizeof(char) == 1 Void void x ;// error void f() ;// function does not return a value void* pv ;// pointer to unknown type

30 Enumerations An enumeration is a type that can hold a set of values specified by the user. It is used like an integer type. Example: enum { ASM, AUTO, BREAK } ; // ASM==0, AUTO==1, BREAK==2 Orenum keyword { ASM, AUTO, BREAK } ; void f(keyword key) { switch(key) { case ASM :// do something break ; case BREAK :// do something break ; } }

31 Declarations and Definitions Before an identifier can be used it must be declared (or defined), to inform the compiler what kind of entity the name refers char ch ;// NO VAL string s ;// NO VAL int count = 1 ; const double pi = 3.1415926535897932385 ; extern int error_number ;// NO DEF char* name = “Haim” ; char* season [ ] = { “spring”, “summer”, “fall”, “winter” } ; struct Date { int d, m, y ; } ; int day(Date* p) { return p->d ; } double sqrt(double) ;// NO DEF template T abs(T a) { return a<0 ? –a : a ; } typedef complex Point ; struct User ;// NO DEF enum Beer { Carlsberg, Tuborg, Macabi } ; namespace NS { int a; }

32 Declarations and Definitions Some definitions do not have pre-declarations double sqrt(double) { /*…*/ } int error_number = 1 ; struct User { /*…*/ } Declaring/Defining multiple names int* p, y;// int*p; int y; int x, *q;// int x; int*q; int v[10], *pv; // int v[10]; int* pv; Name Starts with letter or underscore and consists of letters, underscores and digits

33 Scope A definition introduces a name into a scope. int x;// Global void f() { int x;// Local x hides global x x=1;// Assign to local x ::x=4;// Assign to global x {int x;// Hides previous local x x=2;// Assign to second local x } x=3;// Assign to first local x } int* p=&x;// Take address of global x

34 Initialization int a ;// a is 0 double d ;// d is 0.0 void f() { int x ;// x is not initialized } int arr[]={1,2} ;// Array Initialization Point z(1,2) ;// Constructor Initialization int f() ;// Function declaration lvalue : Expression that refers to an object, that is modifiable. *p[a+10] = 7 ; Typedef : Declares a new name typedef char* PChar ; PChar p1, p2 ;

35 Advices 1. Keep scopes small 2. Don’t use the same name in both a scope and an enclosing scope 3. Declare one name per declaration 4. Keep common and local names short, and uncommon and non-local names longer 5. Avoid similar-looking names 6. Maintain a consistent naming style 7. Choose names to reflect meaning rather then implementation 8. Use a typedef to define a meaningful name for a built-in type in cases in which the built in type used to represent a value might change 9. Use typedefs to define synonyms for types; use enumerations and classes to define new types 10. Do not make assumptions on the size of integers/Objects 11. Do not make assumptions on the range of floating-point types 12. Avoid unsigned arithmetic 13. View conversions with suspicion. Like signed to unsigned and vice verse, floating-point to integer, int to char, etc.

36 Pointers, Arrays, and Structures

37 Pointers For a type T, T* is “pointer to T” A variable of type T* can hold the address of an object of type T. Example: char c = ‘a’ ; char* p = &c ;// p holds the address of c c: p: &c ‘a’

38 Pointers Pointer Examples int* pi ;// pointer to int char** ppc ;// pointer to pointer to char int* ap[15] ;// array of 15 pointers to int int (*fp)(char*) ;// pointer to function int* f(char*) ;// function Dereferencing char c = ‘a’ ; char* p = &c ;// p holds the address of c char c2 = *p ;// c2 is assigned the value pointed by p Zero NULL : const int NULL = 0 ;

39 Arrays For a type T, T[size] is “array of size elements of T.” Index from 0 to size-1. Examples float v[3] ;// array of 3 floats, v[0], v[1] and v[2] char* a[32] ;// array of 32 pointers to char void f(int i) { int v1[i] ;// Error vector v2(i) ;// OK } int d2[10][20] ;// Array of 10 arrays of 20 integers int v1[] = {1,2,3,4} ; char v4[3] = {‘a’, ‘b’, 0}

40 Arrays String Literals “this is a string” ; sizeof(“Arik”)==5 ; // const char[5], last char is ‘\0’ const char* errorMessage() { /*…*/ return “Range-Error” ; }// Statically allocated cout << “End of the message\n” ;// New Line Pointers into Arrays int v[]={1,2,3,4} ; int* p1 = v ; int* p2 = &v[0] ; int* p3 = &v[4] ; 1234 v: p1p2 p3

41 Arrays Implicit conversion extern “C” int strlen(const char*); // from void f() { char v[] = “Wonderful Life” ; char* p=v ;// Implicit conversion from char[] to char* strlen(p) ; strlen(v) ;// Implicit conversion from char[] to const char* // v = p ;// Error; Cannot assign into array } Navigating Arrays void fi(char v[]) { for (int i=0;v[i]!=0;++i) use(v[i]) ; } void fp(char v[]) { for (char* p=v;*p!=0;++p) use(*p) ; }

42 Pointer Arithmetic Pointer Address #include int main() { int vi[10] ; short vs[10] ; std::cout << &vi[0] << ‘ ‘ << &vi[1] << endl ; std::cout << &vs[0] << ‘ ‘ << &vs[1] << endl ; } // Produces : 0x7fffaef0 0x7fffaef4 //0x7fffaedc 0x7fffaede Pointer Addition, Subraction void f() { int v1[10] ; int v2[10] ; int i1 = &v1[5]-&v1[3] ; // 2 int i2 = &v1[5]-&v2[3] ;// Result undefined int* p1 = v2+2;// p1=&v2[2] ; int* p2 = v2-2 ;// *p2 is undefined }

43 Constants const values doesn’t change directly const int model=90 ;// model is a constant const int v[]={1,2,3} ;// v[i] is a constant const int x ;// Error: No Initializer void f() { model=200; // Error v[2]++ ;// Error } const parameters void g(const X* p) { // can’t modify *p here } void h() { X val ; g(&val) ;

44 Pointers and Constants Pointers involve two objects. The Value pointed to and the pointer. void f1(char*p) { char s[]=“Mediterranean” ; const char* pc=s;// pointer to constant pc[3]=‘m’;// Error pc=p;// Ok char *const cp=s;// constant pointer cp[3]=‘m’;// Ok cp=p;// Error const char *const cpc=s;// const pointer to const cpc[3]=‘m’;// Error cpc=p;// Error }

45 References A reference is an alternative name for an object. void f() { int i=1; int& r=i; // r and i refer to the same int int x=r;// x is 1 r=2; // i is 2 } void g() { int i=1; int& r=i; int* p=&r; r++;// i is 2 (*p)++;// i is 3 }

46 References Reference can be used as Copy-by-Reference argument to a function void increment ( int & a) { ++a ; } void incr ( int* p ) { ++(*p) ; } int next ( int i ) { return i+1 ; } void g() { int x = 1 ; increment (x) ;// x is 2 incr (&x) ;// x is 3 x = next (x) ;// x is 4 }

47 Pointer to void Any pointer can be assigned to void*, and void* can be explicitly converted to any pointer void f ( int* pi ) { void* pv = pi ;// implicit conversion *pv ;// error. Cannot dereference void* pv++ ;// error. Cannot increment void* int* pi2 = static_cast (pv) ;// explicit conversion to int* double* pd1=pv;// error double* pd2=pi;// error double* pd3=static_cast (pv);// unsafe } Allocation into void* void* my_alloc(size_t n);// allocate n bytes from the heap

48 Structures A struct is an aggregate of elements of arbitrary types. struct Address { char* name ; // “Moshe Levy” long int id ;// 123456789 char* street ;// “Jabotinsky 33” char* city ;// “Ramat Gan” long zip ;// 34567 } void f() { Address a ; a.name = “Moshe Levy” ; a.id = 123456789 ; } Address ad = { “Moshe Levy”, 123456789, “Jabotinsky 33”, “Ramat Gan”, 34567” }

49 Structures void print_addr ( Address* p ) { cout name << “\n” id << “\n” street << “\n” town << “\n” zip << “\n” ; } Address current ; Address setCurrent ( Address next ) { Address prev = current ; current = next ; return prev ; }

50 Structures The name is immediately available struct Link { Link *prev ; Link *next ; int value ; } struct NoGood { NoGood member ;// Error } Pre Definition struct S ; extern S a ; S f() ; void g(S) ; void k(S* p) { S a ;// Error: Size needed f() ;// Error: Size needed to return a value p->m=7;// Error: Member not known S* q=h(p);// Ok }

51 Advice 1. Avoid non-trivial Pointer Arithmetic 2. Take care not to write beyond the bounds of an array 3. Use vector instead of built in arrays 4. Use string instead of ‘\0’ terminated char arrays 5. Minimize use of plain reference arguments 6. Avoid void* except in low-level code 7. Avoid non-trivial literals. Instead define and use symbolic constants.

52 A bit Background to C

53 Functions Function Prototyping (Declaration) The declaration of a function can be given in any place in the program int translate (float x, float y, float z); In prototyping argument names are optional int translate (float, float, float); Function definition The definition must be done only once. The argument names must be given since they are referenced inside the definition int translate (float x, float y, float z) { return x + y * z ; }

54 Functions Return value type must be specified int f1(void); // Returns an int, takes no arguments int f2(); // Like f1() in C++ float f3(float, int, char, double); // Returns a float void f4(void); // Takes no arguments, returns nothing Return value must be returned in the definition // Return.cpp // Use of "return" #include using namespace std; char cfunc(int i) { if(i == 0) return 'a'; return 'c'; } int main() { cout > val; cout << cfunc(val) << endl; }

55 Parameter-Passing Function Parameters Pass-by-value: a copy of that argument is made inside the function // PassByValue.cpp void f(int a) { a = 6; } int main() {int x = 48; f(x); int y = x;// x and y are 48 } Pass-by-reference: An alias of the passed name // PassByValue.cpp void f(int& a) { a = 6; } int main() { int x = 48; f(x); int y = x;// x and y are 6 }

56 Parameter-Passing Examples We can pass-by-reference effect by passing pointer // PassByPointer.cpp void f(int* a) { *a = 6; } int main() {int x = 48; f(&x); int y = x;// x and y are 6 } Some Examples void f1(char c, int i, float f, double d); void f2(short int si, long int li, long double ld); void f3(char* cp, int* ip, float* fp, double* dp); void f4(char& cr, int& ir, float& fr, double& dr);

57 Control Statements C++ Control Statements if-else while do-while for switch goto

58 Control Statementsif-else if(expression) statement OR if(expression) statement else statement Expression must evaluate to true or false Statement must be in { } in case it has more then once command

59 Control Statements -if-else // Ifthen.cpp // Demonstration of if and if-else conditionals #include using namespace std; int main() { int i; cout > i; if(i > 5) cout << "It's greater than 5" << endl; else if(i < 5) cout << "It's less than 5 " << endl; else cout << "It's equal to 5 " << endl; }

60 Control Statements - while The statement is repeated until the expression is false while (expression) statement The expression is evaluated once at the beginning of the loop and again before each further iteration of the statement Example // Guess.cpp // Guess a number (demonstrates "while") #include using namespace std; int main() { int secret = 15; int guess = 0; while (guess != secret) { // Compound statement cout > guess; } cout << "You guessed it!" << endl; }

61 Control Statements – do-while do statement while (expression); The expression is evaluated after the first loop if it is true the next iteration is done before checking it again Example // Guess2.cpp // The guess program using do-while #include using namespace std; int main() { int secret = 15; int guess; // No initialization needed here do { cout > guess; // Initialization happens } while (guess != secret); cout << "You got it!" << endl; }

62 Control Statements -for for ( initialization; conditional; step) statement The initialization code executes once at the very beginning. The conditional is tested before each iteration (if it evaluates to false at the beginning, the statement never executes). At the end of each loop, the step executes. Example: // Charlist.cpp // Display all the ASCII characters // Demonstrates "for" #include using namespace std; int main() { for ( int i = 0; i < 128; i = i + 1) if (i != 26) // ANSI Terminal Clear screen cout << " value: " << i << " character: " << char(i) << endl; }

63 Control Statements - break and continue statements break quits the loop without executing the rest of the statements in the loop. continue stops the execution of the current iteration and goes back to the beginning of the loop to begin a new iteration. Example // Menu.cpp // Simple menu program demonstrating the use of "break" and "continue" #include using namespace std; int main() { char c; // To hold response while(true) { cout "; cin >> c; if(c == 'q') break; if(c == 'l') { /* … Do something … */ continue; } if(c==‘r’) { /* … Do something … */ continue ; } cout << “Error!” << endl ; }

64 Control Statements -switch A switch statement selects from among pieces of code switch(selector) { case integral-value1 : statement; break; case integral-value2 : statement; break; case integral-value3 : statement; break; (...) default: statement; }

65 Control Statements -switch //: C03:Menu2.cpp // A menu using a switch statement #include using namespace std; int main() { bool quit = false; // Flag for quitting while(quit == false) { cout > response; switch(response) { case 'a' : cout << "you chose 'a'" << endl; break; case 'b' : cout << "you chose 'b'" << endl; break; case 'c' : cout << "you chose 'c'" << endl; break; case 'q' : cout << "quitting menu" << endl; quit = true; break; default : cout << "Please use a,b,c or q!" << endl; } } }

66 Auto-Increment/Decrement ++iincrements i and returns the new value i++ increments i and returns the previous values --idecrements i and returns the new value i--decrements i and returns the previous value Example // AutoIncrement.cpp // Shows use of auto-increment and auto-decrement operators. #include using namespace std; int main() { int i = 0; int j = 0; cout << ++i << endl; // Pre-incrementprints cout << j++ << endl; // Post-increment cout << --i << endl; // Pre-decrement cout << j-- << endl; // Post decrement }

67 Scoping The variables are available within their scope from the point they are defined. void main() { // no variables int i1 ; // i1 is available here { // i1 is available here, but not i2 int i2 ; // i1 and i2 are available here } // i1 is available here but not i2 }

68 Dynamic Object Creation

69 Not always we know the exact quantity, type, and lifetime of the objects in a program. We need to create and destroy objects at runtime. Dynamic Memory allocation in C void* malloc(int size); void* calloc(int num,int size); void* realloc(void*,int size); void free(void*); These methods allocates/frees blocks of memory on the heap This will not work in C++ for Objects, since One can forget to initialize the object One can accidentally do something to the object before it is initialized Hand it the wrong-sized object.

70 C’s approach for Memory Allocation in C++ // MallocClass.cpp // Malloc with class objects. What you'd have to do if not for "new“. #include // malloc() & free() #include using namespace std; class Obj { void initialize() // Can't use constructor { cout << "initializing Obj" << endl; } void destroy() const // Can't use destructor { cout << "destroying Obj" << endl; } }; int main() { Obj* obj = (Obj*)malloc(sizeof(Obj)); obj->initialize(); //... sometime later: obj->destroy(); free(obj); }

71 Dynamic Object Creation When a C++ object is created 1. Storage is allocated for the object. 2. The constructor is called to initialize that storage. Storage can be allocated Before the program begins, in the static storage area. Storage can be created on the stack Storage can be allocated from the heap

72 Dynamic Object Creation Dynamic Memory allocation in C++ Allocating one object with new operator MyType *fp = new MyType; // Default Constructor MyType *fp = new MyType(1,’a’);// Another constructor Freeing one object with delete operator delete fp; Allocating an array of objects with new[] operator MyType* fparr = new MyType[100]; // Only Default Constructor Freeing a list of objects with delete[] operator delete[] fparr;

73 Dynamic Object Creation Example // Stack.h // Stack: LIFO: It allows to insert and to get numbers in // The number to be get next is the one inserted more recently class Stack { private: int* arr ; // The list of numbers is kept here int size ;// The size of the numbers in the stack int capacity ; // The capacity of the array void resize() ; public: Stack() { size=0; capacity=10; arr=new int[capacity] ; } ~Stack() { delete [] arr ; } void put(int next) ; int get() ; bool isEmpty() { return size==0 ; } };

74 Dynamic Object Creation Example // Stack.cpp : The definitions for some functions of Stack void Stack::put(int next) { if (size==capacity) resize() ; arr[size++] = next ; } int Stack::get() { return arr[--size] ; } void Stack::resize() { capacity *= 2 ; int* narr = new int[capacity] ; for (int i=0;i<size;++i) *(narr+i) = *(arr+i) ; delete [] arr ; arr = narr ; }

75 Dynamic Object Creation Example // StackUsage.cpp // Trying the Stack Class #include using namespace std; int main() { Stack stack; stack.put(10) ; stack.put(20) ; stack.put(30) ; while (! stack.isEmpty()) cout << “The next number get: “ << stack.get() << endl ; } // Prints in order: 30, 20, and 10

76 Exercises 1. Write class Queue. It will work as a FIFO. The element will exit in the same order they are inserted. 2. Write class String that can grow infinitely. It will have a default ctor will start with an empty internal string. Function append(const char*) adds the given string into the end of the internal string. Reminder: The string in C is a character array ending with ‘\0’.


Download ppt "Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008."

Similar presentations


Ads by Google