OOMPA Lecture 14 - PowerPoint PPT Presentation

1 / 129
About This Presentation
Title:

OOMPA Lecture 14

Description:

... Paul McCartney, John Lennon, Ringo Starr and George Harrison are members of the Beatles. ... song 'Hey Jude' is composed by Paul Mc Cartney and John Lennon. ... – PowerPoint PPT presentation

Number of Views:53
Avg rating:3.0/5.0
Slides: 130
Provided by: unkn651
Category:

less

Transcript and Presenter's Notes

Title: OOMPA Lecture 14


1
OOMPA Lecture 14
  • Exam solutions
  • Together demo
  • Introduction to C

2
Together
  • Together ( http//www.togethersoft.com )
  • Model-build-deploy tool
  • Creation, editing of UML diagrams
  • Synchronization between UML diagrams and source
    code
  • GoF patterns
  • JAVA, C, C
  • Free limited version available at
    http//www.togethercommunity.com/
  • Demo ..\..\..\..\Together5.5\bin\Together.exe

3
Exam
  • Master solution available on course webpage
  • Evaluation scheme will be available
  • Exam results by November 2nd, 2001
  • Grading
  • 22 out of 38 betyg 3
  • 26 out of 38 betyg 4
  • 30 out of 38 betyg 5

4
Question 1
  • Question 1 (1) Abstract methods have
  • No program code in the subclass FALSE
  • Program code in the defining class FALSE
  • Program code in the subclasses CORRECT
  • No program code in the defining class CORRECT
  • (b) and (c)
  • (c) and (d)
  • (a) and (b)
  • Correct answer f

5
Question 2
  • Question 2 (1) An association is
  • a.      A straight line in a class diagram FALSE
  • b.     Represented by a noun that describes the
    interaction FALSE
  • c.      A relationship between instances of
    classes CORRECT
  • d.     A relationship between classes FALSE
  • e.      (a) and (d)
  • f.       (b) and (c)
  • Correct answer c

6
Question 3
  • Question 3 (1) Aggregation
  • a.      Means an object is built of other objects
    FALSE
  • b.     Means an object contains other objects
    CORRECT
  • c.      Is always of multiplicity 1- FALSE
  • d.     Is is a kind of relationship FALSE
  • e.      (b) and (c)
  • f.       (a) and (d)
  • Correct answer b

7
Question 4
  • Question 4 (1) Which of the following statements
    are true for statechart diagrams
  • a.      An event is caused by a transition. FALSE
  • b.     An object has to be in exactly one state
    at a time. CORRECT
  • c.      A state is a condition needed for a
    transition to occur. FALSE
  • d.     In a transition one or more attributes
    change their value. MAYBE
  • e.      (a) and (c)
  • f.       (b) and (d)
  • Correct answer f , but b also counts as a
    correct answer since changing state does not
    necessarily means that the object changes its
    attributes, but for example it could simply
    change the control flow.

8
Question 5
  • Question 5 (1) Generalization is
  • a.      building objects from parts FALSE
  • b.     a has a-relationship FALSE
  • c.      a is a kind-of relationship CORRECT
  • d.     realized by means of inheritance CORRECT
  • e.      realized by means of composition FALSE
  • f.       (a) and (b)
  • g.      (c) and (d)
  • h.      (a) and (e)
  • i.       (a), (b) and (e)
  • Correct answer g

9
Question 6
  • Question 6 (1) Polymorphism
  • a.      requires abstract classes FALSE
  • b.     is realized by means of static binding
    FALSE
  • c.      is realized by means of dynamic binding
    CORRECT
  • d.     enables subclasses to override the method
    of a superclass CORRECT
  • e.      (a),(c) and (d)
  • f.       (a) and (c)
  • g.      (c) and (d)
  • h.      (b) and (d)
  • Correct answer g

10
Question 7
  • Question 7 (4) Which of the following phrases
    best describe the design patterns in the list.
    Match 10 out of 14 phrases with the 10 concepts
    below.
  • a.   Proxy-   Provide a placeholder for another
    object to control access to it.
  • b.    Adapter- Convert the interface of a class
    into another interface clients expect.
  • c.      Low Coupling- Supports low dependency and
    low impact of change.
  • d.     Composite - Lets clients treat individual
    and group of objects uniformly.
  • e.      Factory Method - Lets a class defer
    instantiation to subclasses.
  • f.       Abstract Factory - Provide an interface
    for creating families of related objects without
    specifying their concrete classes.
  • g.      Singleton - Provides global access to a
    unique instance
  •    

11
Question 7
  • h.    Observer-  When one object changes its
    state the state of dependant objects is
    synchronized.
  • i.     Expert - A class that has the information
    necessary to fulfill a responsibility.
  • j.     Pure Fabrication - Assign responsibilities
    to an artificial class to support high cohesion
    and low coupling.
  • k.     Controller - An object responsible for
    receiving or handling system events.
  • l.     Strategy - Define a family of algorithms
    and make them interchangeable.
  • m.    Façade -  Provide a unified interface to a
    set of interfaces in a subsystem.
  • n.       Mediator - An intermediate object that
    decouples other objects.

12
Question 8
  • Question 8 (2) Describe in two sentences what is
    the difference between object oriented analysis
    and design.
  • OO analysis is concerned with
  • finding and describing objects or concepts in
    the problem domain.
  • what needs to be done.
  • defining the problem/requirements (do the right
    thing)
  • OO design is concerned with
  • defining software objects and how they
    collaborate
  • how is it done
  • conceiving a solution to the problem (do the
    thing right)

13
Question 9
  • Question 9 (2) What is (usually) the
    multiplicity (1.., .., etc.) of the following
    associations?
  • a.               Brother is sibling of sister
    -
  • b.               Child is a descendant of parent
    1..-2
  • c.               Person is married with person
    0,1-0,1
  • d.               Twin is sibling of twin 1-1
  • e.               Student attends course - or
    -1..
  • f.                Flight flies to airport -1 or
    -
  • g.               Order contains items 1-1..
  • h.               Customer purchases product -
    or 0,1-

14
Question 10
  • Question 10 (2) Describe in two sentences the
    roles of inception and elaboration within the
    unified process.
  • Answer Inception is a feasibility study which
    envisions the product scope, approximate vision
    and business case. Elaboration generates a
    refined vision, iterative implementation of core
    architecture, resolution of high risks,
    identification of most requirements and scope.
    (see Larman pages 35 and 109).

15
Question 11
  • Question 11 (1) In the unified process
    requirements are described by
  • a.               Design model FALSE
  • b.               Domain model FALSE
  • c.               Use case model CORRECT
  • d.               (a) and (b)
  • e.               (a) and (c)
  • f.                (b) and (c)
  • Correct answer c

16
Question 12
  • Question 12 (1) Extreme Programming advocates
  • a.               continuous integration CORRECT
  • b.               a sequential, linear lifecycle
    FALSE
  • c.               Refactoring CORRECT
  • d.               (a) and (b)
  • e.               (a) and (c)
  • f.                (b) and (c)
  • g.               (a), (b) and (c)
  • Correct answer e

17
Question 13
  • Question 13 (8) A vending machine offers two
    different products A and B. Product A costs 4
    SEK, product B 6 SEK. The customer inserts one
    coin at a time into the slot. The machine accepts
    coins in denominations of 1, 5 or 10 SEK. The
    machine displays the amount available for
    purchasing products. The machine has three
    buttons, button A to dispense product A, button B
    to dispense product B and button C to obtain
    change. At any time the customer can press button
    C to collect her change or amount paid, even if
    no purchase occurred previously. The customer can
    press buttons A and B at any time, but the
    machine only dispenses the corresponding product
    if the current amount paid is equal to or exceeds
    the product price. It is possible to make
    multiple purchases with one payment by using the
    remaining amount for another purchase (for
    example inserting a 10 SEK coin and purchasing
    product A twice and obtain 2 SEK change or for
    example inserting a 5 SEK coin, purchasing
    product A, inserting another 5 SEK coin and
    purchasing product B).
  • a.   Draw a state diagram for the vending
    machine.
  • b.   Draw a system sequence diagram for a
    scenario in which the customer inserts two 5 SEK
    coins, purchases product B and collects her
    change. Illustrate the information or product the
    vending machine shows or dispenses to the
    customer.

18
Question 13 State-Diagram
  • States Idle, Coins Inserted, Product A
    dispensable, Product A B dispensable
  • Events insert coin, button A, button B, return
    button
  • Actions dispense A, dispense B, return change

19
Question 13
20
Question 13
21
Question 13
22
Question 14
  • Question 14 (4) Draw the collaboration diagram
    that corresponds to the following sequence
    diagram

23
Question 14
24
Question 15
  •  Question 15 (8) Draw a domain model as a UML
    class diagram, containing concepts,
    generalizations, named associations with
    multiplicity (composition and aggregation where
    applicable) and attributes for the following
    domain. The task is to design a software that
    helps you keep track of your collection of audio
    CDs. One distinguishes between two different
    types of releases, namely maxi-CDs and album CDs.
    Each release (album or maxi-CD) contains one or
    several recordings, a recording is a particular
    song performed by a particular artist, for
    example the album Hot Rocks by the Rolling
    Stones contains recordings of the songs Time is
    on my side, Heart of Stone, Play with Fire
    etc. Each recording has a playing time, for
    example Time is on my side has a playing time
    of 523. The same recording might occur on
    different releases, for example the original
    studio album and a best-of album..

25
Question 15
  • The same or a different artist might perform the
    same song in different recordings, for example
    the song American Pie by Don Mc Lean and
    Madonna or Sympathy for the Devil in a live and
    a studio version by the Rolling Stones. One
    distinguishes between solo artists (e.g. Madonna)
    and bands composed of artists, for example Paul
    McCartney, John Lennon, Ringo Starr and George
    Harrison are members of the Beatles. An artist
    can occur on different recordings in different
    roles, either as a solo artist or a band member,
    for example Sting as a solo artist or as a member
    of the band Police. A song has a title and is
    composed by one or several composers, for example
    the song Hey Jude is composed by Paul Mc
    Cartney and John Lennon. Each release has a
    title, release date, music label and a playing
    time that is calculated as the accumulated
    playing time of the recordings on the release. A
    release is usually associated with one particular
    solo artist or band, for example the album Abbey
    Road with the Beatles. Still, this is not always
    the case for example in case of movie sound
    tracks or events such as Woodstock, which feature
    a number of different artists on the same release

26
Question 15
Concepts composer, song, recording, release,
artist, solo artist, band, album, maxi-CD
27
Differences between JAVA and C
  • C uses pointers instead or in addition to JAVA
    references
  • C also uses references but in a different way
    than JAVA
  • C has no garbage collection, which means that
    objects created with new have to be destroyed
    with delete in order to avoid memory leaks
  • JAVA is an interpreter language (virtual
    machine), portable across platforms (byte code is
    somehow between assembler code and source code)
  • C programs need to be compiled separately for
    each target platform.

28
Additonal Features of C
  • Pointers
  • Operator overloading
  • Template methods and classes
  • Multiple inheritance
  • Standard Template Library (container classes)

29
Hello World
  • include ltiostreamgt // input-output library
  • int main() // function main
  • cout ltlt Hello World ltlt endl //
    standard output stream

30
Output Using Cout
  • The identifier cout is actually an object. It is
    predefined
  • in C and corresponds to the standard output
    stream.
  • A stream is an abstraction that refers to a flow
    of data.
  • The operator ltlt is called the insertion or put
    operator
  • and can be cascaded (like arithmetic
    operators ,-,,/)
  • It directs the contents of the variable to the
    right to
  • the object to the left.

string strHello world int i8 cout ltlt str ltlt
endl // endl inserts a new line cout ltlt i
ltlt i ltlt endl // cascade operator ltlt
variable/ constant
standard output device
cout
ltlt
31
Input Using Cin
  • The object cin is predefined in C and
    corresponds
  • to the standard input stream.
  • The gtgt operator is called the extraction or get
    operator
  • and takes the value from the stream object to
    the left
  • and places it in the variable on its right.
  • The stream represents data coming from the
    keyboard

int temperature cout ltlt Enter temperature in
Celsius cin gtgt temperature
standard input device
cin
variable
gtgt
32
Library Functions
  • Many activities in C/C are carried out by
    library functions.
  • These functions perform file access, data
    conversion and
  • mathematical computations.
  • include ltmathgt // includes the declaration
    file for
  • // mathematical functions
  • int main()
  • double x3.14
  • cout ltlt sin(3.14) ltlt sin(x) ltlt endl

33
Header Files
  • a header file contains the declaration of
    functions
  • you want to use in your code
  • the preprocessor directive include takes care
    of
  • incorporating a header file into your source
    file
  • example
  • include ltmathgt
  • include myprog.h
  • the brackets ltgt indicate that the compiler first
    searches
  • the standard include directory which contains
    the
  • standard C/C header files first
  • the quotation marks indicate that the compiler
    first searches
  • for header files in the local directory
  • if you do not include the appropriate header
    file
  • you get an error message from the compiler

34
Header and Library Files
library header file
include ltsomelibgt
myprog.C
somelib.h
user header file
include myprog.h
myprog.h
compiler
library file
object file
myprog.o
libm.a
linker
executable file
myprog
35
Makefile
  • A Makefile is a recipe for how to cook a
    product
  • The necessary operations are divided into single
    steps which partially depend on each other
  • Example Change a flat tire on a car
  • Actions
  • get_jack, get_spare_tire, lift_car,
    remove_flat_tire, attach_spare_tire, lower_car,
    stow_away_jack, stow_away_flat_tire, drive_away
  • Dependencies
  • lift_car get_jack
  • remove_flat_tire lift_car
  • attach_spare_tire get_spare_tire
  • stow_away_flat_tire remove_flat_tire
  • lower_car attach_spare_tire
  • stow_away_jack lower_car
  • drive_away stow_away_flat_tire
    stow_away_jack

36
Makefile
user header file
mat.C
lab1.C
mat.h
source file
include mat.h
g c mat.C
compiler
compiler
g c lab1.C
mat.o
lab1.o
object file
linker
libm.a
g lab1.o mat.o -lm
executable file
a.out
math library file
37
Makefile
  • Assume you have two source files mat.C and lab1.C
  • from which you are supposed to create a
    program a.out
  • all a.out
  • lab1.o depends on lab1.C and mat.h
  • lab1.o lab1.C mat.h
  • g -c lab1.C
  • mat.o depend on mat.C and mat.h
  • mat.o mat.C mat.h
  • g -c mat.C
  • a.out depends on lab1.o and mat.o
  • a.out lab1.o mat.o
  • g mat.o lab1.o -lm

38
Makefile
  • define a variable CC for the name of the
    compiler
  • CCg
  • define compiler flags for warnings and
    debugging
  • CCFLAGS-Wall -g
  • define a variable OBJS for the objects needed
    to build the program
  • OBJSmat.o lab1.o
  • overall target
  • all a.out
  • explain for all cc source files how to build an
    object file
  • .o .C
  • (CC) (CCFLAGS) -c lt
  • a.out (OBJS)
  • g (OBJS) -lm

39
Passing by Value
  • when passing arguments by value, the function
    creates
  • new local variables to hold the values of the
    variable
  • argument
  • the value of the original variable are not
    changed
  • void f(int val) // the parameter val holds a
    local copy of the
  • // variable argument
  • val
  • int x4
  • f(x) // call function f passing x by value
  • cout ltlt x // x still has the value 4

40
Passing by Reference
  • a reference provides an alias a different name
    for a variable
  • when passing arguments by reference the local
    variable
  • is an alias for the original variable
  • the memory address of the variable is passed
    such that the
  • function can access the actual variable in the
    calling program
  • void swap (int a, int b) // call by reference
    a,b are aliases
  • int tmp
  • tmp a
  • a b
  • b tmp
  • int x3 int y5
  • swap(x,y) // call by reference a,b are aliases
    for x,y

41
Const Parameters/Variables
  • passing by reference is efficient when passing
    large data
  • structures as it avoids copying the variable
  • a const reference guarantees that the function
    cannot
  • modify the value of the passed argument
  • an attempt to change the value of a const
    variable or
  • parameter is caught at compile time
  • void f( int a, const int b ) // argument b is
    constant
  • const int c8 // defines variable c as a
    constant
  • a5 // ok
  • b7 // error cannot modify const parameter
  • c7 // error cannot modify const variable

42
Class Definition (Interface)
  • class Date // declares class name
  • private // not visible outside the
    class
  • int day, month, year // member
    data
  • public // visible interface
  • Date(int d, int m, int y) //
    constructor
  • void add_year(int n) // add n
    years
  • void add_month(int n) // add n
    months
  • void add_day(int n) // add n
    days
  • void show_date() // displays
    date

  • // do not forget the here !!!

43
Class Implementation
  • void DateDate(int d, int m, int y)
  • dayd
  • monthm
  • year y
  • void Dateadd_month(int n)
  • monthn
  • year (month-1)/12
  • month (month-1) 12 1

44
Class Implementation
  • include ltiostreamgt
  • void Dateshow_date() // Date specifies
    that show_date is a
  • //
    member function of class Date
  • cout ltlt day ltlt . ltlt m ltlt . ltlt y ltlt endl
  • void Dateadd_year(int n)
  • yeary
  • void Dateadd_day(int n)
  • .

45
Member Initialization
  • two types of member initialization in class
    constructor
  • by initialization members are initialized
    before the constructor is executed (necessary for
    data members tha have no default constructor)
  • by assignment members are created per default
    constructor first and then a value is assigned to
    them
  • DateDate(int d, int m, int y) day(d),
    month(m), year(y)
  • DateDate(int d, int m, int y) // assignment
    initialization
  • dayd
  • monthm
  • yeary

46
Constant Member Functions
  • A member function that is declared as constant
    does
  • not modify the data of the object
  • class Date
  • int month() const // const month() does
    not modify attributes of Date
  • void add_year(int n) // non-const
    add_year() modifies attributes of Date
  • int Datemonth() const // defined as const
  • return month
  • int Dateadd_year(int n)
  • yearn

47
Constant Member Functions
  • A const member function can be invoked for const
    and non-const objects, whereas a non-const member
  • function can only be invoked for non-const
    objects
  • Date somedate(12,17,1999)
  • const Date christmas(24,12,2001)
  • int isomedate.month() // ok
  • somedate.add_year(2) // ok
  • int jchristmas.month() // ok month const
    member function
  • christmas.add_year(3) // error add_year
    non-const member

48
Lecture 15
  • C
  • Multiple Inheritance
  • Operator overloading
  • Templates
  • Pointers
  • Dynamic memory allocation
  • Standard Template Library
  • Containers
  • Iterators
  • Algorithms

49
Lecture Schedule
  • Mon 5/11/01 (Bjoern)
  • VisualWorks/Smalltalk
  • Mon 12/11/01 (Frank)
  • C
  • Game playing (lab4)
  • Course evaluation
  • Tue 20/11/01 (Bjoern)
  • VisualWorks/Smalltalk

50
Inheritance
subclass
super class
Feature A
Feature A
Feature B
Feature B
Feature C
Feature D
51
Inheritance
  • class Date
  • public // visible outside class scope
  • int Year()
  • protected // visible to sub-classes but
    hidden from rest of the world
  • int day, month, year
  • class DateTime public Date
  • public
  • int Hours()
  • private // only visible to class DateTime
  • int hours, minutes

52
Multiple Inheritance
subclass
base class A
Feature A
Feature A
Feature B
Feature B
Feature C
base class B
Feature D
Feature C
Feature D
53
Multiple Inheritance
  • class Date
  • public
  • int Year()
  • private
  • int day, month, year
  • class Time
  • public
  • int Hours()
  • private
  • int hours, minutes

54
Multiple Inheritance
  • class DateTime public Date, public Time
  • public
  • DateTime(int d, int m, int y, int h, int
    mi)
  • DateTimeDateTime(int d, int m, int y, int h,
    int mi)
  • Date(d,m,y), Time(h, mi)

55
Ambiguity in Multiple Inheritance
  • class Date
  • void add(int days)
  • class Time
  • void add(int minutes)
  • Class DateTime public Date, public Time
  • DateTime dt(13,2,1998,23,10)
  • dt.add(3) // ambiguous -- will not compile
  • dt.Dateadd(4) // uses add of class Date
  • dt.Timeadd(5) // uses add of class Time

56
Ambiguity in Multiple Inheritance
  • class A public void F()
  • class B public A
  • class C public A
  • class D public B, public C
  • D d
  • d.F() // ambiguous - wont compile

class A
diamond shaped inheritance tree
class B
class C
class D
57
Overloading Operator
  • Operator overloading is a useful feature of
    object
  • oriented programming
  • Operator overloading allows it to give normal C
    operators such as ,-,,lt additional meanings
  • It makes statements more intuitive and readable
  • for example
  • Date d1(12,3,1989)
  • Date d2
  • d2.add_days(d1,45)
  • // can be written with the operator as
  • d2d145

58
Operator Overloading
  • The name of an operator function is the keyword
  • operator followed by the operator itself.
  • class complex
  • double re, im // re and im part of a
    complex number
  • public
  • complex (double r, double i) re(r), im(i)
    //constructor
  • complex operator(complex c) // operator
    function
  • complex c1(2.2,3.0) // instantiate complex c1
  • complex c2(1.0,-4.5) // instantiate complex c2
  • complex c3c1c2 // shorthand notation for
    c1 c2
  • complex c4c1.operator(c2) // explicit call

59
Overloading Unary Operators
  • class Date
  • Date operator() // prefix increment
    operator
  • Date Dateoperator ()
  • if (day gt days_in_month())
  • day1
  • if (month gt 12)
  • month1
  • year
  • return this
  • Date d1(31,12,1999)
  • d1 // results in 1.1.2000

60
Overloading Unary Operators
  • class Date
  • Date operator(int) // postfix increment
    operator
  • Date Dateoperator (int)
  • Date old(this)
  • if (day gt days_in_month())
  • day1
  • if (month gt 12)
  • month1
  • year
  • return old
  • Date d1(31,12,1999) Date d2

61
Overloading Binary Operators
  • class Date
  • Date operator(int days) const
  • Date Dateoperator(int days) const
  • Date tmpthis // copy object
  • for (int i0 i lt days i)
  • tmp
  • return tmp
  • Date d1(1,4,1999)
  • Date d2d125 // results in 26.4.2000

62
Overloading Binary Operators
  • class Date
  • Date operator(int days) // must be
    reference as modifies

  • // the left hand argument
  • Date Dateoperator(int days) // return type
    reference to object
  • for (int i0 i lt days i)
  • this
  • return this // return reference to
    object
  • Date d1(1,4,1999)
  • d125 // results in 26.4.2000

63
Overloading Relational Operators
  • class Date
  • bool operator(Date d)
  • return (dayd.day) (monthd.month)
    (yeard.year)
  • bool operatorlt(Date d)
  • if (year lt d.year)
  • return true
  • else
  • if (yeard.year) (month lt d.month)
  • return true
  • else
  • return (monthd.month) (day lt
    d.day)

64
Overloading Binary Operators
  • int Dateoperator-(Date d) const
  • int days0
  • if (this gt d)
  • while (this ! d)
  • days
  • else
  • while (this ! --d)
  • days--
  • return days
  • Date d1(24,4,1988)
  • Date d2(13,3,1998)
  • int diff d1-d2 // diff 42

65
Templates
  • A template is a place-holder for an arbitrary
    built-in
  • or user-defined data type
  • Templates make is possible to use one
  • function or class to handle many different
    data types
  • Function templates allow a parameter to assume an
    arbitrary data-type
  • Class templates allow a member data to assume an
  • arbitrary data-type
  • Templates are another example for polymorphism

66
Function Templates
  • int max(int a, int b) // one max function for
    int
  • if (agtb)
  • return a
  • else
  • return b
  • double max(double a, double b) // max function
    for double
  • if (agtb)
  • return a
  • else
  • return b

67
Function Templates
  • template ltclass Typegt // class Type placeholder
    for concrete data type
  • Type max( Type a, Type b) // substitute
    templateType for concrete type
  • if (agtb) return a else return b //
    identical code
  • void main()
  • int a3, b2
  • Date d1(17,5,1998) // assume operator gt is
    defined for class Date
  • Date d2(23,6,1997)
  • int cmax(a,b) // template T replaced with
    int
  • char zmax(f,q) // template T replaced
    with char
  • Date d3max(d1,d2) // template T replaced
    with date

68
Function Templates
one function template in source file
template ltclass Tgt T max(T a, T b)
argument type determines function instantiation
Date d1,d2,d3 d3max(d1,d2)
char c1,c2,c3 c3max(c1,c2)
int i1,i2,i3 i3max(i1,i2)
int max(int a, int b)
char max (char a, char b)
Date max (Date a, Date b)
69
Class Templates Array.h
  • template ltclass Typegt // template class Type
  • class Array // array of arbitrary data type
  • public
  • Array(unsigned int sz)
  • Type operator(unsigned int i) // returns a
    reference to i-th element
  • Type operator()(unsigned int i) // returns the
    value of i-th element
  • private
  • static int max_size100
  • unsigned int size
  • Type array100 // placeholder for concrete
    data type

70
Class Templates Array.C
  • include Array.h
  • template classltTypegt
  • ArrayltTypegtArray(unsigned int sz)
  • if (sz gt max_size)
  • sizemax_size
  • else
  • sizesz
  • template classltTypegt
  • Type ArrayltTypegtoperator(unsigned int i)
  • if (iltsize)
  • return arrayi
  • template classltTypegt
  • Type ArrayltTypegtoperator()(unsigned int i)
  • if (iltsize)
  • return arrayi

71
Class Templates
  • Arrayltdoublegt x(20) // instantiates a double
    array of size 20
  • ArrayltDategt dates(10) // instantiates a Date
    array of size 10
  • Date christmas(24,12,2001)
  • x105.7 // operator returns reference can
    be used on rhs
  • dates3christmas
  • x11x(10)3.4 // operator () returns value
    can only be used on lhs
  • x01.2
  • for (int i1 ilt20i)
  • xix(i-1)1.2
  • for (int i0 ilt10i)
  • datesi // increment all dates by one
    calendar day

72
Class Templates
  • G has two compiler options
  • -fexternal-templates
  • -fno-external-templates
  • The later compiler directive is the default one
    and you need to arrange for all necessary
    instantiations to appear in the implementation
    file (.C) for example in Array.C
  • include Array.h
  • template classltTypegt
  • ArrayltTypegtArray(unsigned int sz)
  • ...
  • ...
  • template class Arrayltdoublegt // explictly
    instantiate Arrayltdoublegt
  • template class ArrayltDategt // explictly
    instantiate ArrayltDategt

73
Pointers
  • Pointers
  • Pointers and Arrays
  • Pointers and function arguments
  • Dynamic memory management
  • New and delete

74
Pointers
  • Pointers are used to
  • Access array elements
  • Passing arguments to functions when the function
    needs to modify the original argument
  • Passing arrays and strings to functions
  • Obtaining memory from the system
  • Creating data structures such as linked lists
  • Many operations that require pointers in C can be
    carried out without pointes in C using
    reference arguments instead of pointers, strings
    instead of char arrays or vectors instead of
    arrays
  • Some operations still require pointers, for
    example creating data structures such as linked
    lists and binary trees

75
Pointers
  • Each variable in a program occupies a part of the
    computers memory, for example an integer
    variable occupies 4 bytes of memory
  • The location of the piece of memory used to store
    a variable is called the address of that variable
  • An address is some kind of number similar to
    house numbers in a street that is used to locate
    the information stored in that particular variable

int i
address of i
0x1054
10101011
00001111
0x1055
10001000
0x1056
11100011
0x1057
00111011
0x1058
char c
address of c
10111100
0x1059
short s
address of s
11001100
0x1060
76
Pointer Variables
  • A pointer variable is a variable that holds
    address values
  • Each data type has its own pointer variable,
    pointer to int, pointer to double, pointer to
    char,
  • C/C uses the address-of operator to get the
    address of an variable
  • C/C uses the indirection or contents-of
    operator to access the value of the variable
    pointed by
  • int i17
  • int ptr // defines a pointer to an integer
    variable
  • ptr i // assign the address of x to pointer
  • cout ltlt ptr ltlt endl // prints contents of
    variable i

77
Pointer Variables
78
Pointer Variables
  • int v // defines variable v of type int
  • int w // defines variable w of type int
  • int p // defines variable p of type pointer to
    int
  • pv // assigns address of v to pointer p
  • v3 // assigns value 3 to v
  • p7 // assigns value 7 to v
  • pw // assigns address of w to pointer p
  • p12 // assigns value 12 to w
  • Using the indirection operator p to access the
    contents of a variable is called indirect
    addressing
  • or dereferencing the pointer

79
Pointers and Arrays
  • There is a close association between pointers and
    arrays
  • Arrays can be accessed using pointers
  • The name of an array is also a constant pointer
    to the data type of the elements stored in the
    array
  • int array5 23, 5, 12, 34, 17 // array of
    5 ints
  • for (int i0 ilt 5 i)
  • cout ltlt arrayi ltlt endl // using index to
    access elements
  • for (int i0 ilt 5 i)
  • cout ltlt (arrayi) ltlt endl // using pointer
    to access elements
  • // array is of type pointer to integer

80
Pointers as Function Arguments
  • C/C offers three different ways to pass
    arguments to a function
  • by value void f(int x)
  • by reference void f(int x)
  • by pointer void f(int x)
  • In passing by value the function obtains only a
    local copy of the variable, so that changes to
    the local variable have no impact on the argument
    with which the function was invoked
  • In passing by reference and passing by pointer
    the function manipulates the original variable
    rather than only a copy of it

81
Pointers as Function Arguments
  • void swap( double x, double y)
  • double tmpx
  • xy // access variable by its alias name
  • ytmp
  • void swap( double ptr1, double ptr2)
  • double tmpptr1
  • ptr1ptr2 // de-referencing pointer
  • ptr2tmp
  • double a3.0
  • double b5.0
  • swap(a,b) // call by reference to variables a
    and
  • swap(a, b) // call by pointer using the
    addresses of a and b

82
BubbleSort
  • void bsort (double ptr, int n) // pass pointer
    to array and
  • // size of
    array as arguments to bsort
  • int j,k // indices to array
  • for (j0 jltn-1 j) // outer loop
  • for(kj1 kltn k) // inner loop
    starts at outer
  • if((ptrj) gt (ptrk))
  • swap(ptrj,ptrk)
  • double array6 2.3, 4.5, 1.2, 6.8, 0.8, 4.9
  • bsort(array,n) // sort the array

83
Const Modifiers and Pointers
  • The use of the const modifier with pointers is
    confusing as it can mean two things
  • const int cptrInt // cptrInt is a pointer to a
    const int
  • You can not the change the value of the integer
    that cptrInt points to but you can change the
    pointer itself
  • int const ptrcInt // ptrcInt is a constant
    pointer to int
  • You can change the value of the integer that
    ptrcInt points to but you can not change the
    pointer itself

84
Memory Management
  • In order to create an array in C/C you have to
    know its size in advance during compile time, in
    other words it has to be a constant
  • int size
  • cout ltlt Enter size of array
  • cin gtgt size
  • int arraysize // ERROR size has to be a
    constant
  • Solution in C, use vector class from the STL
    which is expandable

85
Memory Management
  • Date CreateDate() // allows the user to create
    a date object
  • int day, month, year
  • char dummy
  • cout ltlt Enter dd/mm/yyyy
  • cin gtgt day gtgt dummy gtgt month gtgt dummy gtgt
    year
  • Date date(day, month, year)
  • return date // ERROR!! Scope of date
    ends with end of function
  • Date ptr
  • ptrCreateDate() // call CreateDate() to
    generate a new date
  • cout ltlt You entered ltlt ptr ltlt endl
  • // variable to which ptr points no longer exist ,
    segmentation fault !!!

86
Memory Management
  • The new operator in C can be used to create
    objects on the heap that are alive after
    returning from a function
  • Objects allocated in dynamic memory are called
    heap objects or to be on free store and have a
    permament existence
  • Date CreateDate() // allows the user to create
    a date object
  • int day, month, year
  • char dummy
  • cout ltlt Enter dd/mm/yyyy
  • cin gtgt day gtgt dummy gtgt month gtgt dummy gtgt
    year
  • Date tmpptr new Date(day, month, year)
  • return tmpptr // returns pointer to heap
    object
  • Date ptr
  • ptrCreateDate() // call CreateDate() to
    generate a new date
  • cout ltlt You entered ltlt ptr ltlt endl // ok,
    ptr refers to heap object

87
Memory Management
  • New can also be used to allocate blocks of memory
  • The delete operator is used to release the memory
    allocated with new once it is no longer needed
  • include ltcstringgt
  • char str This is an old C-style string
  • int lenstrlen(str) // computes the length of
    str
  • char ptr // create a pointer to char
  • ptr new charlen1 // set aside memory
    string \0
  • strcpy(ptr,str) // copy str to new memory
  • cout ltlt ptr ltlt ptr ltlt endl
  • delete ptr // release ptrs memory

88
New Operator in Constructors
  • class String // user-defined string class
  • private
  • char str // pointer to block of
    characters
  • public
  • String(char s) // one-argument constructor
  • int lengthstrlen(s) // length of
    string argument
  • str new charlength1 // allocate
    memory
  • strcpy(str,s) // copy argument to it
  • String() // destructor
  • delete str
  • void Display() cout ltlt str ltlt endl
  • String mystringThis is my string of Type
    String
  • mystring.Display()

89
Pointers to Objects
  • Pointers can point to objects as well as to
    built-in data types
  • Date date // define a named Date object
  • date.Set(12,3,1996) // set the date
  • date.Display() // display the date
  • Date dateptr // define a pointer to a Date
    object
  • dateptrnew Date // points to new Date object
  • dateptr-gtSet(9,12,1999) // set date using -gt
    operator
  • dateptr-gtDisplay() // display date
  • (dateptr).Display() // works as well but less
    elegant

90
Linked List Example
  • A linked list is composed of a chain of elements
    (links). Each element contains some data and a
    pointer to the next element in the list.
  • In a double linked list, each element also
    contains a pointer to its predecessor.

Element
Element
Element
next data
next data
next data
Element
Element
Element
next prev data
next prev data
next prev data
91
Linked List Example
  • struct link // one element of list
  • int data // data item
  • link next // pointer to next element
  • class linklist
  • private
  • link first // pointer to first link
  • public
  • linklist() first NULL // no argument
    constructor
  • void push_back(int d) // add new
    element to the end of list
  • int pop_back() // delete last element
    and return data value
  • void push_front(int d) // add new
    element to the front of list
  • int pop() // delete first element and
    return data value
  • void display() // display all elements
    in list

92
Linked List Example
  • void linklistpush(int d) // add data item at
    the front
  • link newlink new link // create a new
    link
  • newlink-gtdata d // assign new
    data d
  • newlink-gtnextfirst // it points to
    the next link
  • first newlink // now first
    points to this link

93
Linked List Example
  • int linklistpop() // remove element at the
    front
  • int tmp_data first-gtdata
  • link tmpfirst
  • firstfirst-gtnext
  • delete tmp // free storage
  • return tmp_data
  • int linklistpop_back() // remove element at
    the end
  • link tmpfirst
  • while (tmp-gtnext ! NULL)
  • tmptmp-gtnext
  • int tmp_data tmp-gtdata
  • delete tmp // free storage
  • return tmp_data

94
Linked List Example
  • void linklistpush_back(int d) // add data
    item at the end
  • link newlink new link // create a new
    link
  • newlink-gtdata d // assign new
    data d
  • newlink-gtnext 0 // points to nil
  • link tmpfirst
  • if (tmp NULL) // empty list
  • firstnewlink
  • else
  • while (tmp-gtnext!NULL)
  • tmptmp-gtnext
  • tmp-gtnextnewlink // it points to the
    next link

95
Linked List Example
  • void linklistdisplay() // display all links
  • link tmpfirst // set ptr to first link
  • while(tmp ! NULL) // until ptr points
    beyond last link
  • cout ltlt current-gtdata ltlt // print
    data
  • currentcurrent-gtnext //
    move to next link

96
Linked List Example
  • template ltclass Tgt
  • struct link // one element of list
  • T data // data item
  • link next // pointer to next element
  • template ltclass Tgt
  • class linklist
  • private
  • link first // pointer to first link
  • public
  • linklist() first NULL // no argument
    constructor
  • void push(T t) // add data item
    (one link)
  • T pop()
  • void display() // display all
    links

97
Linked List Example
  • template ltclass Tgt
  • void linklistltTgtpush(T t) // add element at
    the front
  • link newlink new link // create a new
    link
  • newlink-gtdata t // give it data
    d
  • newlink-gtnextfirst // it points to
    the next link
  • first newlink // now first
    points to this link
  • template ltclass Tgt
  • void linklistltTgtdisplay() // display all
    links
  • link currentfirst // set ptr to first
    link
  • while(current ! NULL) // until ptr points
    beyond last link
  • cout ltlt current-gtdata ltlt // print
    data
  • currentcurrent-gtnext //
    move to next link

98
Standard Template Library
  • The standard template library (STL) contains
  • Containers
  • Algorithms
  • Iterators
  • A container is a way that stored data is
    organized in memory, for example an array of
    elements.
  • Algorithms in the STL are procedures that are
    applied to containers to process their data, for
    example search for an element in an array, or
    sort an array.
  • Iterators are a generalization of the concept of
    pointers, they point to elements in a container,
    for example you can increment an iterator to
    point to the next element in an array

99
Containers, Iterators, Algorithms
Algorithms use iterators to interact with
objects stored in containers
Container
Container
Iterator
Algorithm
Iterator
Objects
Algorithm
Iterator
Iterator
Algorithm
100
Containers
  • A container is a way to store data, either
    built-in data
  • types like int and float, or class objects
  • The STL provides several basic kinds of
    containers
  • ltvectorgt one-dimensional array
  • ltlistgt double linked list
  • ltdequegt double-ended queue
  • ltqueuegt queue
  • ltstackgt stack
  • ltsetgt set
  • ltmapgt associative array

101
Sequence Containers
  • A sequence container stores a set of elements in
  • sequence, in other words each element (except
  • for the first and last one) is preceded by
    one
  • specific element and followed by another,
    ltvectorgt,
  • ltlistgt and ltdequegt are sequential containers
  • In an ordinary C array the size is fixed and
    can
  • not change during run-time, it is also
    tedious to
  • insert or delete elements. Advantage quick
    random
  • access
  • ltvectorgt is an expandable array that can shrink
    or
  • grow in size, but still has the disadvantage
    that
  • inserting or deleting elements in the middle
    is costly as it requires to copy chunks of memory

102
Sequence Containers
  • ltlistgt is a double linked list (each element has
  • points to its successor and predecessor), it
    is
  • quick to insert or delete elements but
    provides no
  • random access (e.g. return 5th element in list)
  • ltdequegt is a double-ended queue, that means one
  • can insert and delete elements from both ends,
    it
  • is a kind of combination between a stack (last
    in
  • first out) and a queue (first in first out) and
    constitutes a compromise between a ltvectorgt and
  • a ltlistgt

103
Associative Containers
  • An associative container is non-sequential but
    uses
  • a key to access elements. The keys, typically
    a number or a string, are used by the container
    to arrange the stored elements in a specific
    order,
  • for example in a dictionary the entries are
    ordered
  • alphabetically.

104
Associative Containers
  • A ltsetgt stores a number of items which contain
    keys
  • The keys are the attributes used to order the
    items,
  • for example a set might store objects of the
    class
  • Person which are ordered alphabetically using
    their name
  • A ltmapgt stores pairs of objects a key object
    and
  • an associated value object. A ltmapgt is
    somehow
  • similar to an array except instead of
    accessing its
  • elements with index numbers, you access them
    with
  • indices of an arbitrary type.
  • ltsetgt and ltmapgt only allow one key of each value,
  • whereas ltmultisetgt and ltmultimapgt allow
    multiple
  • identical key values

105
Vector Container
int array5 12, 7, 9, 21, 13 vectorltintgt
v(array,array5)
12
7
9
21
13
v.push_back(15)
v.pop_back()
13

12
7
9
21
12
7
9
21
15
0 1 2 3 4
12
7
9
21
15
v.begin()
v3
106
Vector Container
  • include ltvectorgt
  • include ltiostreamgt
  • vectorltintgt v(3) // create a vector of ints of
    size 3
  • v023
  • v112
  • v29 // vector full
  • v.push_back(17) // put a new value at the end
    of array
  • for (int i0 iltv.size() i) // member
    function size() of vector
  • cout ltlt vi ltlt // random access to
    i-th element
  • cout ltlt endl

107
Constructors for Vector
  • A vector can be initialized by specifying its
    size and
  • a prototype element or by another vector
  • vectorltDategt x(1000) // creates vector of size
    1000,
  • //
    requires default constructor for Date
  • vectorltDategt dates(10,Date(17,12,1999)) //
    initializes
  • // all
    elements with 17.12.1999
  • vectorltDategt y(x) // initializes vector y with
    vector x

108
Iterators
  • Iterators are pointer-like entities that are used
    to
  • access individual elements in a container.
  • Often they are used to move sequentially from
    element to element, a process called iterating
    through a container.

vectorltintgt
array_
17
vectorltintgtiterator
4
23
The iterator corresponding to the class
vectorltintgt is of the type vectorltintgtiterator
12
size_
4
109
Iterators
  • The container member functions begin() and end()
    return an iterator to the first and past the last
    element of a container

vectorltintgt v
v.begin()
array_
17
4
23
v.end()
12
size_
4
110
Iterators
  • One can have multiple iterators pointing to
    different or identical elements in the container

vectorltintgt v
i1
array_
17
4
i2
23
12
i3
size_
4
111
Iterators
  • include ltvectorgt
  • include ltiostreamgt
  • vectorltintgt v // initialize empty vector
  • v.push_back(13)
  • v.push_back(9)
  • v.push_back(8)
  • vectorltintgtiterator iterv.begin() //
    iterator for class vector
  • // define iterator for vector and point it to
    first element of v
  • cout ltlt first element of v ltlt iter //
    de-reference iter
  • iter // move iterator to next element
  • iterv.end()-1 // move iterator to last element

112
Iterators
  • int max(vectorltintgtiterator start,
    vectorltintgtiterator end)
  • int tmpmaxstart
  • while(start ! stop)
  • if (start gt tmpmax)
  • tmpmaxstart
  • start
  • return tmpmax
  • cout ltlt max of v ltlt max(v.begin(),v.end())

113
Iterator Categories
  • Not every iterator can be used with every
    container for example the list class provides no
    random access iterator
  • Every algorithm requires an iterator with a
    certain level of capability for example to use
    the operator you need a random access iterator
  • Iterators are divided into five categories in
    which a higher (more specific) category always
    subsumes a lower (more general) category, e.g. An
    algorithm that
  • accepts a forward iterator will also work
    with a bidirectional iterator and a random access
    iterator

input
forward
bidirectional
random access
output
114
For_Each() Algorithm
  • include ltvectorgt
  • include ltalgorithmgt
  • include ltiostreamgt
  • void show(int n)
  • cout ltlt n ltlt
  • int arr 12, 3, 17, 8 // standard C
    array
  • vectorltintgt v(arr, arr4) // initialize vector
    with C array
  • for_each (v.begin(), v.end(), show) // apply
    function show
  • // to each element of vector v

115
Find() Algorithm
  • include ltvectorgt
  • include ltalgorithmgt
  • include ltiostreamgt
  • int key
  • int arr 12, 3, 17, 8, 34, 56, 9 //
    standard C array
  • vectorltintgt v(arr, arr7) // initialize vector
    with C array
  • vectorltintgtiterator iter
  • cout ltlt enter value
  • cin gtgt key
  • iterfind(v.begin(),v.end(),key) // finds
    integer key in v
  • if (iter ! v.end()) // found the element
  • cout ltlt Element ltlt key ltlt found ltlt endl
  • else
  • cout ltlt Element ltlt key ltlt not in vector v
    ltlt endl

116
Find_If() Algorithm
  • include ltvectorgt
  • include ltalgorithmgt
  • include ltiostreamgt
  • Bool mytest(int n) return (ngt21) (n lt36)
  • int arr 12, 3, 17, 8, 34, 56, 9 //
    standard C array
  • vectorltintgt v(arr, arr7) // initialize vector
    with C array
  • vectorltintgtiterator iter
  • iterfind_if(v.begin(),v.end(),mytest)
  • // finds element in v for which mytest is true
  • if (iter ! v.end()) // found the element
  • cout ltlt found ltlt iter ltlt endl
  • else
  • cout ltlt not found ltlt endl

117
Count_If() Algorithm
  • include ltvectorgt
  • include ltalgorithmgt
  • include ltiostreamgt
  • Bool mytest(int n) return (ngt14) (n lt36)
  • int arr 12, 3, 17, 8, 34, 56, 9 //
    standard C array
  • vectorltintgt v(arr, arr7) // initialize vector
    with C array
  • int ncount_if(v.begin(),v.end(),mytest)
  • // counts element in v for which mytest is
    true
  • cout ltlt found ltlt n ltlt elements ltlt endl

118
List Container
  • A list container is a double linked list, in
    which
  • each element contains a pointer to its
    successor and
  • predecessor.
  • It is possible to add and remove elements at any
    location in the list
  • Lists do not allow random access but are
    efficient to
  • insert new elements and to sort and merge
    lists

119
List Container
int array5 12, 7, 9, 21, 13 listltintgt
li(array,array5)
12
7
9
21
13
li.push_back(15)
li.pop_back()
13

12
7
9
21
12
7
9
21
15
li.push_front(8)
li.pop_front()
12

Write a Comment
User Comments (0)
About PowerShow.com