object oriented programming with c++ moshe fresko bar-ilan university 2007-2008

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

Upload: eileen-morrison

Post on 16-Dec-2015

217 views

Category:

Documents


3 download

TRANSCRIPT

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

Object Oriented Programmingwith C++

Moshe FreskoBar-Ilan University

2007-2008

Page 2: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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

Page 3: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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)

Page 4: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Introduction to C++

Page 5: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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.

Page 6: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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.

Page 7: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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

Page 8: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Program Execution Language Translation

The translation of Human-Understandable Code into Machine-Understandable

Two types of Translation1. Interpreter2. Compiler

C++ Compilation Process1. Preprocessor

Optionally also does Global Optimizations2. Compiler

1. First Pass: Creates parse tree2. Second Pass: Creates object modules (*.obj) Optionally also does Peephole Optimizations

3. Linker From a list of Object Files creates an executable

Page 9: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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.

Page 10: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Declaration vs. Definition Functions

Definitionint func1(char, float) { /*…the code…*/ }

Declarationint func1(char, float);

Variables Definition

int a ; Declaration

extern int a ;

Page 11: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Declaration vs. Definition// File: Exemple1.cppextern int i; // Declaration without definitionextern float f(float); // Function declaration

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

}

Page 12: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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>

Page 13: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Using Libraries

For using libraries1. Include the library’s header file.2. Use the functions and variables in

the library.3. Link the library into the executable

program.

Page 14: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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

Page 15: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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

Page 16: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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

}

Page 17: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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 }

Page 18: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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;

}

Page 19: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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

Page 20: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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;

}

Page 21: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Exercises1. 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<float> and put 25 floating-point numbers into it

using a for loop. Display the vector.6. 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.

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

Page 22: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Types and Declarations

Page 23: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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

Page 24: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Fundamental Types Boolean Type

bool Character Types

such as char Integer Types

such as int Floating-Point Types

such as double Absence of

Information Typevoid

Enumeration Typesenum

Pointer Typesint*

Array Typeschar[]

Reference Typesdouble&

Structures and Classesstru { … }class { … }

Page 25: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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

Page 26: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Character Types char holds a character of implementation’s character

set

Example: char ch = ‘a’ ;

Two typessigned char -127 … 127unsigned char0 … 255

For Unicodewchar_t

Character Literals‘a’ ‘0’ ‘\n’ ‘\t’ L’ab’

Page 27: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Integer Types Three forms

intsigned int ( or signed )unsigned int ( or unsigned )

Three sizesshort int ( or short )intlong int ( or long )

Integer LiteralsDecimal: 0 63Octal: 00 077Hexadecimal: 0x0 0x3f

U for Unsigned Literals 63UL for Long Literals 63L

Page 28: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Floating Point Types

Three Sizesfloatdoublelong double

Floating Point Literals1.23 .23 0.23 1.1.0 1.2e10 1.23e-15Suffix F for float 3.1416f 2.0F

Page 29: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Fundamental Types

sizeof(…) gives the size of any type in terms of chars

sizeof(char) == 1

Voidvoid x ; // errorvoid f() ; // function does not return a valuevoid* pv ; // pointer to unknown type

Page 30: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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 somethingbreak ;case BREAK : // do somethingbreak ; }}

Page 31: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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 DEFchar* 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; }

Page 32: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Declarations and Definitions Some definitions do not have pre-declarations

double sqrt(double) { /*…*/ }int error_number = 1 ; struct User { /*…*/ }

Declaring/Defining multiple namesint* 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

Page 33: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Scope A definition introduces a name into a scope.

int x; // Globalvoid f() {

int x; // Local x hides global xx=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

Page 34: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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 ;

Page 35: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Advices1. Keep scopes small2. Don’t use the same name in both a scope and an enclosing scope3. Declare one name per declaration4. Keep common and local names short, and uncommon and non-local

names longer5. Avoid similar-looking names6. Maintain a consistent naming style7. Choose names to reflect meaning rather then implementation8. 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/Objects11. Do not make assumptions on the range of floating-point types12. Avoid unsigned arithmetic13. View conversions with suspicion. Like signed to unsigned and vice

verse, floating-point to integer, int to char, etc.

Page 36: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Pointers, Arrays, and Structures

Page 37: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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’

Page 38: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Pointers Pointer Examples

int* pi ; // pointer to intchar** ppc ; // pointer to pointer to charint* ap[15] ; // array of 15 pointers to intint (*fp)(char*) ; // pointer to functionint* f(char*) ; // function

Dereferencingchar c = ‘a’ ;char* p = &c ; // p holds the address of cchar c2 = *p ; // c2 is assigned the value pointed by p

Zero NULL : const int NULL = 0 ;

Page 39: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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 charvoid f(int i) {

int v1[i] ; // Errorvector<int> v2(i) ; // OK

} int d2[10][20] ; // Array of 10 arrays of 20 integersint v1[] = {1,2,3,4} ;char v4[3] = {‘a’, ‘b’, 0}

Page 40: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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 Arraysint v[]={1,2,3,4} ;int* p1 = v ; int* p2 = &v[0] ;int* p3 = &v[4] ; 1 2 3 4v:

p1 p2 p3

Page 41: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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

Page 42: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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, Subractionvoid f() {

int v1[10] ; int v2[10] ;int i1 = &v1[5]-&v1[3] ; // 2int i2 = &v1[5]-&v2[3] ; // Result undefinedint* p1 = v2+2; // p1=&v2[2] ;int* p2 = v2-2 ; // *p2 is undefined

}

Page 43: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Constants const values doesn’t change directly

const int model=90 ; // model is a constantconst int v[]={1,2,3} ; // v[i] is a constantconst int x ; // Error: No Initializervoid f() {

model=200; // Errorv[2]++ ; // Error

} const parameters

void g(const X* p) {// can’t modify *p here

}void h() {

X val ;g(&val) ;

Page 44: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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; // Okchar *const cp=s; // constant pointercp[3]=‘m’; // Okcp=p; // Errorconst char *const cpc=s; // const pointer to constcpc[3]=‘m’; // Errorcpc=p; // Error

}

Page 45: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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 intint x=r; // x is 1r=2; // i is 2

}

void g() {int i=1;int& r=i;int* p=&r;r++; // i is 2(*p)++; // i is 3

}

Page 46: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

References Reference can be used as Copy-by-Reference

argument to a functionvoid 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 2incr ( &x) ; // x is 3x = next (x) ; // x is 4

}

Page 47: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Pointer to void Any pointer can be assigned to void*, and void* can be

explicitly converted to any pointervoid 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; // errordouble* pd2=pi; // errordouble* pd3=static_cast<double*>(pv); // unsafe

}

Allocation into void*void* my_alloc(size_t n) ; // allocate n bytes from the

heap

Page 48: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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

Page 49: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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

}

Page 50: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Structures The name is immediately available

struct Link {Link *prev ;Link *next ;int value ;

}struct NoGood {

NoGood member ; // Error}

Pre Definitionstruct S ;extern S a ;S f() ;void g(S) ;void k(S* p) {

S a ; // Error: Size neededf() ; // Error: Size needed to return a

valuep->m=7; // Error: Member not

known S* q=h(p); // Ok}

Page 51: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Advice1. Avoid non-trivial Pointer Arithmetic2. Take care not to write beyond the

bounds of an array3. Use vector instead of built in arrays4. Use string instead of ‘\0’ terminated

char arrays5. Minimize use of plain reference

arguments6. Avoid void* except in low-level code7. Avoid non-trivial literals. Instead define

and use symbolic constants.

Page 52: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

A bit Background to C

Page 53: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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 definitionint translate (float x, float y, float z)

{ return x + y * z ; }

Page 54: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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 <iostream> using namespace std; char cfunc(int i) {

if(i == 0) return 'a'; return 'c';

} int main() {

cout << "type an integer: "; int val; cin >> val; cout << cfunc(val) << endl;

}

Page 55: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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

}

Page 56: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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

Page 57: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Control Statements

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

Page 58: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Control Statementsif-elseif(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

Page 59: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Control Statements - if-else

// Ifthen.cpp // Demonstration of if and if-else conditionals #include <iostream> using namespace std;

int main() { int i; cout << "type a number and 'Enter'" << endl; cin >> 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;

}

Page 60: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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 <iostream> using namespace std; int main() {

int secret = 15; int guess = 0; while (guess != secret) { // Compound statement

cout << "guess the number: "; cin >> guess;

} cout << "You guessed it!" << endl;

}

Page 61: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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 <iostream> using namespace std; int main() {

int secret = 15; int guess; // No initialization needed here

do { cout << "guess the number: "; cin >> guess; // Initialization happens

} while (guess != secret); cout << "You got it!" << endl;

}

Page 62: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Control Statements - forfor ( 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 <iostream> 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; }

Page 63: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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 <iostream> using namespace std; int main() { char c; // To hold response while(true) { cout << "MAIN MENU:" << endl << “l: left, r: right, q: quit -> "; cin >> c; if(c == 'q') break; if(c == 'l') { /* … Do something … */ continue; } if(c==‘r’) { /* … Do something … */ continue ; } cout << “Error!” << endl ; }}

Page 64: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Control Statements -switch A switch statement selects from among

pieces of codeswitch(selector) {

case integral-value1 : statement; break; case integral-value2 : statement; break; case integral-value3 : statement; break; (...) default: statement;

}

Page 65: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Control Statements -switch

//: C03:Menu2.cpp // A menu using a switch statement #include <iostream> using namespace std; int main() { bool quit = false; // Flag for quitting while(quit == false) { cout << "Select a, b, c or q to quit: "; char response; cin >> 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; } } }

Page 66: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Auto-Increment/Decrement ++i increments i and returns the new value i++ increments i and returns the previous values --i decrements 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 <iostream> using namespace std; int main() {

int i = 0; int j = 0; cout << ++i << endl; // Pre-increment prints cout << j++ << endl; // Post-incrementcout << --i << endl; // Pre-decrement cout << j-- << endl; // Post decrement

}

Page 67: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Scoping The variables are available within their scope

from the point they are defined.

void main() {// no variablesint i1 ;// i1 is available here{

// i1 is available here, but not i2int i2 ;// i1 and i2 are available here

}// i1 is available here but not i2

}

Page 68: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Dynamic Object Creation

Page 69: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Dynamic Object Creation 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.

Page 70: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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 <cstdlib> // malloc() & free() #include <iostream> 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); }

Page 71: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Dynamic Object Creation

When a C++ object is created1. 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

Page 72: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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;

Page 73: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Dynamic Object CreationExample

// Stack.h// Stack: LIFO: It allows to insert and to get numbers in// The number to be get next is the one inserted more recentlyclass Stack { private:

int* arr ; // The list of numbers is kept hereint size ; // The size of the numbers in the stackint capacity ; // The capacity of the arrayvoid 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 ; }

};

Page 74: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Dynamic Object CreationExample

// Stack.cpp : The definitions for some functions of Stackvoid 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 ;

}

Page 75: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

Dynamic Object CreationExample

// StackUsage.cpp // Trying the Stack Class #include <iostream> 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

Page 76: Object Oriented Programming with C++ Moshe Fresko Bar-Ilan University 2007-2008

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