Object oriented programming with c
Download
1 / 76

Object Oriented Programming with C - PowerPoint PPT Presentation


  • 250 Views
  • Updated On :

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.

loader
I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
capcha
Download Presentation

PowerPoint Slideshow about 'Object Oriented Programming with C' - hye


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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
Object oriented programming with c l.jpg

Object Oriented Programmingwith C++

Moshe Fresko

Bar-Ilan University

2007-2008


Course requirements l.jpg
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


Resources l.jpg
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)



History l.jpg
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.


History6 l.jpg
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.


Introduction to c7 l.jpg
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


Program execution l.jpg
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


Declaration vs definition l.jpg
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.


Declaration vs definition10 l.jpg
Declaration vs. Definition

  • Functions

    • Definition

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

    • Declaration

      int func1(char, float);

  • Variables

    • Definition

      int a ;

    • Declaration

      extern int a ;


Declaration vs definition11 l.jpg
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); }


Header files l.jpg
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>


Using libraries l.jpg
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.


First c program hello cpp l.jpg
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


Some c examples number conversion l.jpg
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; }


Some c examples string class l.jpg
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; }


Some c examples file input output l.jpg
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 }


Some c examples fill string l.jpg
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; }


Some c examples vector class l.jpg
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; }


Some c examples vector with integers l.jpg
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; }


Exercises l.jpg
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.



Types and declarations23 l.jpg
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


Fundamental types l.jpg

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


Booleans l.jpg
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


Character types l.jpg
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’


Integer types l.jpg
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


Floating point types l.jpg
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


Fundamental types29 l.jpg
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


Enumerations l.jpg
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 ; }

    }


Declarations and definitions l.jpg
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; }


Declarations and definitions32 l.jpg
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


Scope l.jpg
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


Initialization l.jpg
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 ;


Advices l.jpg
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.



Pointers l.jpg
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’


Pointers38 l.jpg
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 ;


Arrays l.jpg
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}


Arrays40 l.jpg
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


Arrays41 l.jpg
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) ;

    }


Pointer arithmetic l.jpg
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

    }


Constants l.jpg
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) ;


Pointers and constants l.jpg
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

    }


References l.jpg
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

    }


References46 l.jpg
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

    }


Pointer to void l.jpg
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


Structures l.jpg
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” }


Structures49 l.jpg
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 ;

}


Structures50 l.jpg
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}


Advice l.jpg
Advice

  • Avoid non-trivial Pointer Arithmetic

  • Take care not to write beyond the bounds of an array

  • Use vector instead of built in arrays

  • Use string instead of ‘\0’ terminated char arrays

  • Minimize use of plain reference arguments

  • Avoid void* except in low-level code

  • Avoid non-trivial literals. Instead define and use symbolic constants.



Functions l.jpg
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 ; }


Functions54 l.jpg
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; }


Parameter passing l.jpg
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}


Parameter passing examples l.jpg
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);


Control statements l.jpg
Control Statements

  • C++ Control Statements

    • if-else

    • while

    • do-while

    • for

    • switch

    • goto


Control statements if else l.jpg
Control Statements if-else

if(expression)

statement

ORif(expression)

statement

else

statement

  • Expression must evaluate to true or false

  • Statement must be in { } in case it has more then once command


Control statements if else59 l.jpg
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; }


Control statements while l.jpg
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; }


Control statements do while l.jpg
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; }


Control statements for l.jpg
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 <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; }


Control statements break and continue statements l.jpg
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 ;

    }

    }


Control statements switch l.jpg
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; }


Control statements switch65 l.jpg
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; } } }


Auto increment decrement l.jpg
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-increment cout << --i << endl; // Pre-decrement cout << j-- << endl; // Post decrement }


Scoping l.jpg
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

    }



Dynamic object creation69 l.jpg
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.


C s approach for memory allocation in c l.jpg
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); }


Dynamic object creation71 l.jpg
Dynamic Object Creation

  • When a C++ object is created

    • Storage is allocated for the object.

    • 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


  • Dynamic object creation72 l.jpg
    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;


    Dynamic object creation example l.jpg
    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 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 ; }

    };


    Dynamic object creation example74 l.jpg
    Dynamic Object CreationExample

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

    }


    Dynamic object creation example75 l.jpg
    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


    Exercises76 l.jpg
    Exercises

    • Write class Queue. It will work as a FIFO. The element will exit in the same order they are inserted.

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


    ad