1 / 76

Object Oriented Programming with C++

Object Oriented Programming with C++. Moshe Fresko Bar-Ilan University 2006-2007. Course Requirements. Goals To learn basics of Object Oriented Programming To program in C++ Practically see Design Paradigms Exercises In total 5 exercises

habib
Download Presentation

Object Oriented Programming with C++

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Object Oriented Programmingwith C++ Moshe Fresko Bar-Ilan University 2006-2007

  2. Course Requirements • Goals • To learn basics of Object Oriented Programming • To program in C++ • Practically see Design Paradigms • Exercises • In total 5 exercises • Final exercise grade will be the average of 4 best • Exercises will be 20% of the final grade • Exam • 80% of the final grade • No-material is allowed in the exam

  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 • History • 1980 C with classes • 1983 Name C++ is given • 1985 Version 1.0 (Basics) • 1987 Standardization Process • 1989 ANSI C++ • 1989 Version 2.0 (Multi-inheritance, Operator Overloading) • 1991 Version 3.0 (Templates) • 1995 Standard 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 • Interpreter • Compiler • C++ Compilation Process • Preprocessor • Optionally also does Global Optimizations • Compiler • First Pass: Creates parse tree • Second Pass: Creates object modules (*.obj) • Optionally also does Peephole Optimizations • 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 definitionextern float f(float); // Function declarationfloat b; // Declaration & definition floatfloat 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 <header> • Old style vs. New Style Libraries #include <iostream.h> #include <iostream> #include <stdio.h> #include <cstdio>

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

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

  15. Some C++ Examples Number Conversion // Numconv.cpp // Converts decimal to octal and hex #include <iostream> using namespace std; int main() { int number; cout << "Enter a decimal number: "; cin >> 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 <string> #include <iostream> using namespace std; int main() { string s1, s2; // Empty strings string s3 = "Hello, World."; // Initialized 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++ ExamplesFile Input Output // Scopy.cpp // Copy one file to another, a line at a time#include <string> #include <fstream> 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++ ExamplesFill String // FillString.cpp // Read an entire file into a single string #include <string> #include <iostream> #include <fstream> using namespace std; int main() { ifstream in(“File.txt”); string s, line; while(getline(in, line)) s += line + "\n”; cout << s; }

  19. Some C++ Examplesvector class // Fillvector.cpp // Copy an entire file into a vector of string#include <string> #include <iostream> #include <fstream> #include <vector> using namespace std; int main() { vector<string> 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++ Examplesvector with integers // Intvector.cpp // Creating a vector that holds integers #include <iostream> #include <vector> using namespace std;int main() { vector<int> 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 • Using Numconv.cpp as guidelines, create a program that asks for the radius of a circle and prints the area of that circle. • Create a program that opens a file and counts the whitespace-separated words in that file. • Change Fillvector.cpp so that it prints the lines (backwards) from last to first. • Display a file a line at a time, waiting for the user to press the “Enter” key after each line. • Create a vector<float> and put 25 floating-point numbers into it using a for loop. Display the vector. • Create three vector<float> 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. • Create a vector<float> 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. Types and Declarations • Consider x = y + f(2) ; • To make it meaningful for C++ float x ; // x is a floating point variableint y = 7 ; // y is an integer variable // initialized to 7float f(int) ; // f is a function taking argument // type integer and returning // floating point number

  24. 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 { … } Fundamental Types

  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  0 true  1 • int to bool 0  false Non-zero  true

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

  27. Integer Types • Three forms intsigned int ( or signed ) unsigned int ( or unsigned ) • Three sizes short int ( or short )intlong int ( or long ) • Integer Literals Decimal: 0 63 Octal: 00 077Hexadecimal: 0x0 0x3f U for Unsigned Literals 63UL for Long Literals 63L

  28. Floating Point Types • Three Sizes floatdoublelong double • Floating Point Literals 1.23 .23 0.23 1. 1.0 1.2e10 1.23e-15 Suffix F for float 3.1416f 2.0F

  29. Fundamental Types • sizeof(…) gives the size of any type in terms of chars sizeof(char) == 1 • Void void x ; // errorvoid f() ; // function does not return a valuevoid* 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 Or enum 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 VALstring s ; // NO VALint 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 DEFtemplate<class T> T abs(T a) { return a<0 ? –a : a ; } typedef complex<short> Point ;struct User ; // NO DEFenum 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 • Initialization int a ; // a is 0double d ; // d is 0.0void f() { int x ; // x is not initialized} int arr[]={1,2} ; // Array InitializationPoint z(1,2) ; // Constructor Initializationint 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 • Keep scopes small • Don’t use the same name in both a scope and an enclosing scope • Declare one name per declaration • Keep common and local names short, and uncommon and non-local names longer • Avoid similar-looking names • Maintain a consistent naming style • Choose names to reflect meaning rather then implementation • 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 • Use typedefs to define synonyms for types; use enumerations and classes to define new types • Do not make assumptions on the size of integers/Objects • Do not make assumptions on the range of floating-point types • Avoid unsigned arithmetic • 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 p: &c 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<int> 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] ; p3 p1 p2 v: 1 2 3 4

  41. Arrays • Implicit conversion extern “C” int strlen(const char*); // from <string.h> 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 <iostream> 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 constantpc[3]=‘m’; // Errorpc=p; // Ok char *const cp=s; // constant pointercp[3]=‘m’; // Okcp=p; // Error const char *const cpc=s; // const pointer to constcpc[3]=‘m’; // Errorcpc=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<int*>(pv) ; // explicit conversion to int* double* pd1=pv; // error double* pd2=pi; // error double* pd3=static_cast<double*>(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 ; // 123456789char* 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 << p->name << “\n” << p->id << “\n” << p->street << “\n” << p->town << “\n” << p->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}

More Related