CS 325 - PowerPoint PPT Presentation

1 / 46
About This Presentation
Title:

CS 325

Description:

A 'friend' class is responsible for allowing access to the elements in the container ... Write a reverse list iterator for either the doubly linked list or for ... – PowerPoint PPT presentation

Number of Views:34
Avg rating:3.0/5.0
Slides: 47
Provided by: dyes
Category:

less

Transcript and Presenter's Notes

Title: CS 325


1
CS 325
  • Unix Programming Environment
  • and
  • Windows Programming
  • with Microsoft Foundation Classes (MFC)

2
Lecture 7
  • Today
  • Iterator design pattern
  • Inheritance

3
Useful string functions
  • The operator concatenates two strings
  • Compare strings using lt, lt, , gt, gt
  • strn references char n, so does str.at(n)
  • Str.length() returns the length of the string
  • str.find(substring) finds substring
  • str.find(char) finds character
  • find( ) returns stringnpos (a constant, perhaps
    -1) if not found
  • int fooa.find('z')
  • if (foo stringnpos) not found

4
Design Patterns
  • Patterns and Pattern Languages are ways to
    describe best practices, good designs, and
    capture experience in a way that it is possible
    for others to reuse this experience.
  • Big concern of 325 is scaling up your software
    skills
  • Must be able to
  • Read and understand other implementations
  • Build classes that are able to be used in a
    variety of applications
  • Our first design pattern
  • An iterator for lists

5
The Iterator Design Pattern
  • Programs using container classes need to be
    able to look at all the elements in the container
  • Consider a LIST class
  • Want to be able to print all the items
  • Want to be able to find an item
  • Want to be able to print all possible pairs of
    items
  • Some of these could embed in LIST itself
  • Others are more awkward to embed
  • Dont know all possible ways to examine LIST
  • Should processing List look different from
    processing all elements of another container?
  • What if we move from a LIST to a STACK this
    design pattern minimizes the affected code

6
Iterator Assumptions
  • Basic class exists for the container
  • This class creates the underlying data structure,
    and handles adding/removing from the container
  • A friend class is responsible for allowing
    access to the elements in the container
  • Initialize the iterator
  • Get the item the iterator currently points to
  • Increment the iterator to the next item in the
    list
  • Check to see if the iterator has reached the end
    of the list

7
Implementing the Iterator
  • include ltiostream.hgt
  • class Node int dataNode next
  • publicNode() data(0), next(0)
    friend class Listfriend class ListIter
  • class List Node head friend class ListIter
  • publicList() head(0) void add(int e)
  • class ListIter Node current
  • publicListIter(List theList) current
    theList.head int done(void) return current
    0 int get(void) return current-gtdata
    void next(void) if (current)
    currentcurrent-gtnext

8
Using the Iterator
  • This program prints out all possible pairs of
    items in the list. It uses two iterators to
    control the two loops.
  • void main(void) List aa.add(10) a.add(20)
    a.add(30)ListIter y(a)while ( ! y.done() )
    ListIter z(a) int b y.get() while ( !
    z.done() ) coutltltbltlt" "ltltz.get()ltltendl z.ne
    xt() y.next()

9
Using the Iterator
  • template
  • ltclass IT1, class IT2, class Eltgt
  • / T1 and T2 are iterator classes
  • Elt is the type of objects in containers beneath
    T1 and T2, container types are unknown /
  • void example(IT1 it1, IT2 it2)
  • Elt e1, e2
  • it1.Reset()while ( y.HasMoreElts() )
    it1.GetValue(e1) it2().Reset() while
    (it2.HasMoreElts() ) it2.GetValue(e2) Print
    (e1,e2)
  • it2.Next() it1.Next()
  • All possible pairs
  • Of items in two
  • container. Two
  • iterators control
  • the two loops.
  • template ltclass Egt
  • void Print(E a, E b)
  • cout ltlt
  • altlt"\t"ltltb
  • ltltendl

10
Why do we need iterator pattern?
  • Consider the process of reporting a set of
    figures. Does the report change if the figures
    are stored in a heap rather than a binary tree?
    We can store figures in a list, stack, table,
    red-black tree, vector, queue, dequeue, or any
    other container. The process of finding the sum
    or average is dependant on the container.
  • The iterator pattern lets us write reports based
    on the reports needs rather than the container
    the initial data was contained in.

11
Consider 10 reports and 7 containers
  • Data can be in any container depending where in
    the process it is. Thus each report must be used
    with each container.
  • 70 combinations
  • 70 projects to code
  • 70 projects to debug
  • OR
  • Write 7 iterators
  • Write 10 reports based on iterator pattern

12
Class Exercises
  • Re-write the List Iterator code using templates.
  • Write an iterator for the stack class

13
Homework Exercises
  • Add an output operator for CSList using the
    iterator class so that you can print the list.
  • Can you generalize this so that it works on any
    container?
  • consider
  • template ltclass iter, class container, class eltgt
  • Maybe not be able to use output operator this
    way, could certainly define a generalized Print
    function
  • template ltListIterltintgt, Listltintgt, intgt
  • Print (Listltintgt theList)
  • ListIterltintgt it(theList)
  • while (it.HasMoreElts())
  • cout ltlt it.GetVal() ltlt"\t"
  • cout ltlt endl

14
Object-Oriented Programming
  • 3 major ideas in object-oriented programming
  • Encapsulation (hiding/protecting data(cs124))
  • Generalization (templates)
  • Inheritance (next)

15
Classes Inheritance
  • Want efficient techniques to develop code
  • Method 1 Templatesdefine a class generically,
    can plug in any type of data that you want
  • Method 2 Inheritancetake an existing class and
    add to it
  • Inheritance builds off of what already exists
  • Why build from scratch?
  • Find something similar, expand on it
  • Examples
  • Window
  • Account

16
Inheritance
  • What types of things do we obtain from our
    parents?
  • Attributes
  • Behaviors
  • What is a class composed of in general?
  • Data (attributes, data members)
  • Operations upon that data (behaviors, member
    functions, methods)
  • When a class inherits from another class, it
    inherits the attributes and behaviors (data
    members and methods) from its parent class

17
Inheritance
  • Can define attributes and behaviors for a general
    class, then inherit and refine those attributes
    and behaviors to fit a more specific case.
  • Existing class (yours or not yours) may do most
    of what you want, but you want to extend it
    without having to redo what has already been done
  • Parent general
  • Child - specific

18
Inheritance Basic terminology
  • Inheritance extension of an existing class to
    provide necessary/new functionality and promote
    reuse
  • Base Class existing class to be reused (parent)
  • Derived Class class that inherits attributes and
    behaviors of some base class (child, subclass)
  • A derived class can also become a base class of
    another derived class

19
"Is A" vs "Has A" Relationships
  • Has a
  • Deals with construction
  • This room has a door
  • A List has a Node pointer
  • CSQueue has a CSList
  • CSStack has a CSVector
  • Is a (Inheritance)
  • A square is a rectangle
  • An equilateral triangle is a triangle
  • A lab is a room
  • A savings account is a bank account
  • Can define XQueue is a CSList
  • Can define XStack is a CSVector

20
Natural Hierarchies
Shape
Ellipse
Rectangle
Triangle
Equilateral Triangle
Square
21
Class Exercises
  • Think of derived classes (specialized,
    extensions) for the following draw hierarchy.
    Decide what data members and methods would be in
    base classes and the extra data members and
    methods should be added to derived classes
  • class person (in a university setting)
  • class account (financial)
  • class list (single-linked list)

22
private, public w/ inheritance
  • Public any public member of the base class can
    be seen by a derived class
  • Private any private member of the base class
    cannot be seen by a derived class
  • Need Public so derived class can see members
    (else inheritance isnt inheritance)
  • Need Private else we lose the idea of
    encapsulation
  • So
  • Note member may refer to either attributes or
    members (data or functions)

23
protected section
  • There can also be a protected section in a base
    class.
  • This section can be seen by a derived class with
    the is a property
  • This section cannot be seen by other classes
    with a has a property
  • ie
  • Treated as public for purposes of inheritance
  • Treated as private everywhere else

24
Basic Syntax more to come
  • class BaseClass
  • //members methods
  • class DerivedClasspublic BaseClass
  • //new members methods
  • //override methods

25
Classes Inheritance
  • Want efficient techniques to develop code
  • Method 1 Templatesdefine a class generically,
    can plug in any type of data that you want
  • Method 2 Inheritancetake an existing class and
    add to it
  • Inheritance builds off of what already exists
  • Dont build from scratch
  • Find something similar, expand on it

26
Consider a class Pair
  • class Pair
  • int x
  • int y
  • public
  • Pair( ) x(0), y(0)
  • Pair(int a, int b) x(a), y(b)
  • void setX(int a) x a
  • void setY(int a) y a
  • int getX(void) return x
  • int getY(void) return y
  • friend ostream operatorltlt (ostream,
    const Pair)
  • Stores two integers
  • Methods for
  • Setting values
  • Retrieving values
  • Friend operator for output

27
Now want to build a new class
  • Triple stores three integers
  • Need methods to set values
  • Need methods to retrieve values
  • Need friend operator for output
  • Dont want to repeat code unnecessarily
  • Solution build on (inherit from) Pair class
  • Simply add additional functionality to that class
  • Terminology
  • Base class (original class)
  • Derived class (augments, specializes base class)

28
Building the class Triple
  • class Triple public Pair
  • int z
  • public
  • Triple( ) z(0)
  • Triple(int a, int b, int c)
  • Pair(a, b), z(c)
  • void setZ(int a) z a
  • int getZ(void) return z
  • friend ostream operatorltlt
  • (ostream, const Triple)
  • class Pair
  • protected
  • int x
  • int y
  • public
  • Pair( ) x(0), y(0)
  • Pair(int a, int b) x(a), y(b)
  • void setX(int a) x a
  • void setY(int a) y a
  • int getX(void) return x
  • int getY(void) return y
  • friend ostream operatorltlt (ostream,
    const Pair)

29
What Happened?
  • Started with Pair to create Triple
  • Added word protected to Pair
  • Needed for visibility (explain shortly)
  • Class Triple built on top of Pair
  • public Pair implies we are building off of Pair
  • Inherited functions getX, getY, setX, setY
  • Just needed to define setZ, getZ
  • Needed to define new output operator
  • Old one does not work for triple

30
Instantiation
  • //outside of class
  • Pair one
  • Triple two
  • Triple three(3,4,5)

X Y
0
0
X Y Z
0
0
0
X Y Z
5
4
3
31
Class Exercises
  • The file on the web site has the Pair and Triple
    classes in them. Build on this to define a new
    class Quadruplet that contains four integers.
  • Use all three of these classes in a main program
    (set values, print them out).

32
Derived classes
  • Inherit from the base class
  • Members
  • Methods
  • Extends the base class in some way
  • Additional members
  • Additional methods
  • Both additional members additional methods
  • Can also "override" methods (change
    functionality, redefine, etc)

33
Public, Private Protected
  • Up until now, only mentioned public private
    parts to a class
  • public visible to users (outside world)
  • private cannot be seen (except by friends)
  • C actually has three levels of protection
  • private only the class (and friends) can see
  • protected class subclass (and friends) can see
  • public everyone can see

34
Class Exercises
  • Change the protected data in Pair and Triple to
    private.
  • What happens?
  • Can I still declare objects of type Triple and
    Quadruplet?
  • What methods still work for Triple?
  • setX, setY, setZ, getX, getY, getZ
  • What methods still work for Quadruplet?

35
Constructors and Inheritance
  • Since a derived class builds off its base class
  • To instantiate an object in a derived class
  • Initialize base-class members (base constructor)
  • Initialize derived-class members (derived
    constructor)
  • Derived class constructor always calls the
    constructor of its base class first
  • If no constructor exists for derived class,
    default system constructor for derived class
    calls base-class default constructor

36
Class Exercise
  • class Pair
  • protectedint x int y
  • publicPair( ) x(0), y(0) cout ltlt "Pair 1"
    ltlt endl Pair(int a, int b) x(a), y(b)
  • cout ltlt "Pair 2" ltlt endl
  • class Triple public Pair int z
  • publicTriple( ) z(0) cout ltlt "Triple" ltlt
    endl Triple(int a, int b, int c) Pair(a, b),
    z(c) cout ltlt "Triple 2" ltlt endl Triple(int
    a) Pair(), z(a)
  • cout ltlt "Triple 3" ltlt endl
  • What is the output of the following program?
  • void main(void) Pair aTriple bPair
    c(1,2)Triple d(3,4,5)Triple e(6)

37
Another inheritance example
  • Dynamically-allocated linked list of integers
  • Add integers to front of list
  • Node class contains the actual data
  • Extend this class to a doubly-linked list
  • Have a set of forward links
  • Have a set of backward links

Head
Tail
27
38
51
38
2 pointers in our node class
  • class Node
  • int data
  • Node next // forward pointer
  • Node last // backwards pointer
  • public
  • Node( )
  • Node(int e) data(e)
  • friend class List
  • friend class DoubleLinkList

39
Base List Class (forward only)
  • class List
  • protected
  • Node head
  • public
  • List() head(0)
  • void add(int e) Node pnew Node(e)
    p-gtnexthead headp
  • void Print(void) Node p head while (p)
    cout ltlt p-gtdata ltlt " " pp-gtnext cout ltlt
    endl

40
Derived List Class
  • Allows you to traverse forward backward
  • Change add routine (override base version)
  • Change print routine
  • Prints forward then Prints backwards too.
  • No new methods, just re-define existing methods
    to work in this context

41
Derived List Class
  • class DoubleLinkList public List
  • protectedNode tail
  • publicDoubleLinkList() tail(0) void
    add(int e) //left for youvoid Print(void)
    Node p head while (p) cout ltlt p-gtdata
    ltlt " " pp-gtnext cout ltlt endl p
    tail while (p) cout ltlt p-gtdata ltlt " "
    pp-gtlast cout ltlt endl
  • //And there are even better ways

42
Class Exercises
  • Add an output operator for CSList using the
    iterator class so that you can print out the
    list.
  • The file on the web site has the Pair and Triple
    classes in them. Build on this to define a new
    class Quadruplet that contains four integers.
  • Write a reverse list iterator for either the
    doubly linked list or for your project1 code.
  • Use these classes in a main program (set values,
    print them out).

43
Another Inheritance Example
  • Class for Stacks
  • Static-sized stack (maximum of ten elements,
    stored in an array)
  • Separate iterator to print out the stack
  • Define a reversible stack where you can reverse
    the elements in it (reverse method)
  • Any new data members needed?
  • Any new methods needed?
  • Any difference in output (can we still use
    StackIter as a friend)?

44
Original Stack Configuration
  • class StackIter int current, max, ptr
  • publicStackIter(Stack s) current0
    maxs.top ptr s.data int done(void) if
    (current ltmax) return 0 else return 1
    int get(void) return ptrcurrent void
    next(void) current
  • class Stack
  • protectedint data10int top
  • publicStack() top -1 void push(int e)
    datatop e int pop(void) return
    datatop-- friend class StackIter

45
RStack and part of main routine
  • RStack rr.push(10) r.push(20) r.push(30)
    r.push(40)StackIter si2(r)while ( !
    si2.done() ) cout ltlt si2.get() ltlt "
    " si2.next()cout ltlt endlr.reverse()Stack
    Iter si3(r)while ( ! si3.done() ) cout ltlt
    si3.get() ltlt " si3.next()cout ltlt endl
  • class RStack public Stack
  • publicvoid reverse(void)
  • // need code here
  • friend class StackIter

46
Class Exercises
  • Write the reverse function for our reversible
    stack class. The code for the example
    (everything except for the reverse function
    itself) exists on the web
Write a Comment
User Comments (0)
About PowerShow.com