4.1 Advanced Classes

Embed Size (px)

Citation preview

  • 8/20/2019 4.1 Advanced Classes

    1/56

    Advanced Issues on ClassesAdvanced Issues on ClassesPart 1

    - constructor, destructor, copy constructor, deep copy,assignment operator 

      -Tapestry Section 12.3.5 and partially 12.3.3 (a bit limited)

      - Horton parts o !"apter # and $ (detailed discussion)- operator o%erloading

    -Horton pp.&&'... (a bit better)- ppendi * and +.& in Tapestry

    Part 2

    - iterators and riend classes, using static %ariables inclasses

    Part 3  s"aring a %ariable among se%eral obects o t"e

    same class (reerence %ariables, pointers)

  • 8/20/2019 4.1 Advanced Classes

    2/56

    2

    Constructor Constructor !onstructors are special member uctions o a class.

    "en an obect o a class is created, !// calls t"e constructor   or t"atclass.

    Properties0

      !onstructors "a%e t"e same name as t"e class.

      !onstructors do not return any %alues

      !onstructors are in%oed irst "en a class is initiali4ed. nyinitiali4ations or t"e class members, memory allocations are doneat t"e constructor.

    !onstructors may or may not tae parameters

        constructor it" no parameter is called default constructor 

  • 8/20/2019 4.1 Advanced Classes

    3/56

    Default Constructor Default Constructor !onstructor it" no parameter.

     Node::Node()

    {. . . //initialization code

    }

      constructor it" parameters can also be default  i t"e deault %alues ot"ese parameters are pro%ided at declaration. n t"is case, i no

    argument is pro%ided "en t"e constructor is called, deault %alues areused. argument(s) is6are pro%ided, gi%en arguments are used duringconstruction. Node::Node(int num = 0, Node * ptr = NULL)

    {

    . . . //initialization code

    } Node myNode();

     Node myt!erNode ("0);

     Node * ptr = ne# Node();

     Node * ptr$ = ne# Node("0, ptr);

     Node * ptr% = ne# Node ("00);

    3

  • 8/20/2019 4.1 Advanced Classes

    4/56

    Default Constructor Default Constructor "at "appens i t"e programmer does not deine any constructor (it"

    and it"out parameters)  T"e compiler attempts to generate a deault constructor 

      7ot %isible to t"e programmer 

      "en a obect is created t"is deault constructor is in%oedautomatically

      T"is compiler-generated constructor allocates memory or t"eclass pri%ate members and calls deault constructors o t"em (iapplicable)

    4

  • 8/20/2019 4.1 Advanced Classes

    5/56

    5

    Constructor ExampleConstructor Example//point.!

    &i'nde' N+

    &de'ine N+cla-- oint {

     pulic:

    oint(); //de'ault con-tructor

    oint(int , int yy);

    // con-tructor #it! parameter-. . .

     priate:

    int ;

    int y;

    };

    &endi'

    // de'ault con-tructor

    oint::oint() {

    = 0;

      y = 0;

    }

    // con-tructor #it! parameter-

    oint::oint(int , int yy) { = ;

      y = yy;

    }

    Instead of these two constructors you can have

    oint::oint(int =0, int yy=0) { = ;

      y = yy;}

    If no constructor was defined, then a created object would have two

    integers  and y with no initial values

  • 8/20/2019 4.1 Advanced Classes

    6/56

    Using Initializer List in Constructor Using Initializer List in Constructor Synta

    ConstructorHeader   :  privatedata (value),  privatedata(value), . . .

    {

    66 ot"er constructor code comes "ere, eecuted ater assigning %alues in t"e initiali4er list

    }

    *amples

    // de'ault con-tructoroint::oint() : (0), y(0){}

    //1lternatie de'ault con-tructor implementationoint::oint() : (0){

    y = 0;}

    // con-tructor #it! parameter-oint::oint(int , int yy) : (), y(yy){}

  • 8/20/2019 4.1 Advanced Classes

    7/56

    !

    Destructor Destructor 

     "apestr# pp$ 24%25"apestr# pp$ 24%25

    *ac" class s"ould also "a%e a destructor "ic" s"ould tae care oreturning any unreturned memory.

    T"e destructor "as name ~classname()  (put ~ c"aracter beore t"e class

    name)

      7o parameters

      T"is is in t"e class deinition under public

    cla-- Lin2edLi-t{ priate: node * !ead;

     int -ize; pulic: Lin2edLi-t (); 3Lin2edLi-t (); //de-tructor oid printLi-t(); oid addo4e5innin5(int n);//more 'unction- !ere

    };

  • 8/20/2019 4.1 Advanced Classes

    8/56

    &

    Destructor Destructor 8estructor unction is conceptually t"e in%erse o constructor 

    T"ey are called "en an obect is destroyed. Typical ob is to return

    dynamic memory allocated (using new, malloc, calloc) to t"e "eap.

    9ou do not need to tae an action or automatic (regular) data members

    (i.e. t"e ones allocated rom t"e runtime stac). T"ey are automatically

    deallocated.

    Lin2edLi-t::3Lin2edLi-t (){

    node * ptr = !ead; #!ile (ptr 6= NULL)

    { node * temp = ptr78net; delete ptr; ptr = temp;

    }}

  • 8/20/2019 4.1 Advanced Classes

    9/56

    '

    Destructor Destructor T"e destructor is called automatically "en t"e obect goes out o scope.

      :or local (automatic) obects, "en t"e bloc in "ic" t"e obect is

    created inis"es  :or static or global obects, "en t"e program inis"es

    you do not pro%ide a destructor or your class, t"e compiler pro%ides one, but

    t"at;s ust an empty unction, so it does not ser%e any purpose beside

    pro%iding a re

  • 8/20/2019 4.1 Advanced Classes

    10/56

    ()

    Destructor Destructor 

    int !ount=ni input)

    ?

    string ord@

    AinStringSet set@ 66similar to a linedlist o strings@ also "as a si4e ield

    66 AinStringSet is a Tapestry class

    "ile (input BB ord) 66by inserting ords into a CsetD "ic"

    set.insert(ord)@ 66sips t"e insertion i t"e element is already in t"e set

    66e can count "o many elements (ords) are uni

  • 8/20/2019 4.1 Advanced Classes

    11/56

    ((

    Destructor Destructor 

    Since t"e compiler maes t"is call automatically, it creates a a dummy destructor or eac" class t"at does not contain a destructor. So,

      if the programmer has not supplied a destructor, the one which is

    created by the compiler is called

    This basically prevents the program from not compiling, but as a dummy

    function, it is not guaranteed to do the right thing (e.g. doesn’t free all

    memory)

      if the programmer has supplied one, compiler on;t generate a

    dummy destructor 

    Remember that the (real) destructor should free all memory taen with

    !new"#

    $et%s see linedliste&tra class and demo

    (linedliste&tra.cpp) for live e&amples

  • 8/20/2019 4.1 Advanced Classes

    12/56

    (2

    Cop# Constructor* +perator +verloading* AssignmentCop# Constructor* +perator +verloading* Assignment+vervie, and -urpose+vervie, and -urpose

    7o t"at you no "o to rite a class, it" constructor, destructor and necessarymember unctions, e ill loo at more ancy material.

    e are going to see "o t"e unctionality s"on in red, can be ac"ie%ed0

    lin2edli-t li-t", li-t$, li-t%;

    li-t".n-ertrdered(9);

    li-t$.rintLi-t(); //you 2no# !o# to do t!e-e

    G

    li-t$ = li-t"; //a--i5n li-t" to li-t$

    li-t% = li-t" li-t$;  //addition o' li-t-, #it! -uitale meanin5

    lin2edli-t li-t(li-t"); //con-truct li-t 'rom li-t"

    :irst to are typically operators t"at you "a%e come to tae or granted or built-intypes.

    7o you are ased to gi%e t"e same unctionality (as long as meaningul or yourclass).

  • 8/20/2019 4.1 Advanced Classes

    13/56

    Cop# Constructor Cop# Constructor Special constructor called "en an obect is irst declared and initiali4ed rom

    anot"er obect o t"e same type

    *ample0Lin2edLi-t li-t%(li-t);

  • 8/20/2019 4.1 Advanced Classes

    14/56

    Cop# Constructor Cop# Constructor  forfor LinkedListLinkedList ClassClass9ou "a%e to add a prototype to t"e class deinition as ell.

    !aution0 lays use const reerence parameter "ere.

    cla-- Lin2edLi-t{ priate:node * !ead;int -ize;

     pulic: Lin2edLi-t (); Lin2edLi-t (con-t Lin2edLi-t ); //copy con-tructor3Lin2edLi-t (); //de-tructor oid printLi-t() con-t; oid addo4e5innin5(int n); // more 'unction- !ere

    };

    Lin2edLi-t::Lin2edLi-t (con-t Lin2edLi-t copy){

    !ead = copy.!ead;-ize = copy.-ize;

    }

  • 8/20/2019 4.1 Advanced Classes

    15/56

    Cop# Constructor Cop# Constructor 

    T"e copy constructor in t"e pre%ious slide maes s"allo copy @ only t"e

    pri%ate data o a class instance is copied.- n t"e case o a lined list, t"is ould be t"e "ead pointer, 7IT t"e "ole

    list

    - T"e ne list s"are t"e same memory as t"e old oneJ

    AetKs gi%e an eample

    Suppose list1 is lie t"e

    one on t"e rig"t.

     ter Lin2edLi-t li-t$(li-t"); t"e lists become as ollos

    (5

    list(  3 4 5

    list2node . /ead

    int size 0 3

    node . /eadint size 0 3

    list(  3 4 5node . /eadint size 0 3

  • 8/20/2019 4.1 Advanced Classes

    16/56

    Cop# Constructor Cop# Constructor :or e%ery class, t"ere is a default copy constructor  (compiler pro%ided).

    - !ompiler pro%ides t"is i you do not declare a copy constructor.- or eactly as shallow copy mentioned beore

    Simply copies t"e %alue o eac" instance %ariable (e.g. "ead, si4e or

    lined lists) rom one obect to t"e ot"er.

    T"e entire list is not copied.

    S"allo copy may not "at e ant. t may cause se%eral problems.

    - See net slide and letKs see linedlistetra class and demo

    (linedlistetra.cpp) or eample cases.

    -  lso try t"at e do not actually need to deine a copy constructor or s"allo

    copy, deault copy constructor ould do t"e same ob.

    It is always better to use const reference parameters instead of value

    parameters for class types. In value parameter passing implicitly

    copy constructor is invoed. 'sing const reference parameter avoids

    this and une&pected effects of defaultshallow copy constructors and

    destructors.

  • 8/20/2019 4.1 Advanced Classes

    17/56

    1/# /allo, Cop# is ad1/# /allo, Cop# is adLin2edLi-t li-t";

    'or (int 2=0; 2 > ; 2){

    li-t".addo4e5innin5(2");}

    li-t".printLi-t();

    Lin2edLi-t li-t$(li-t");li-t".deleteLi-t();li-t$.printLi-t();

    e want to be able to do this* +ut the program crashes since the list is

    deleted from the memory.

  • 8/20/2019 4.1 Advanced Classes

    18/56

    oodood Cop# Constructor Cop# Constructor  6 Deep Cop# 6 Deep Cop# t"e obect "as dynamically allocated memory, suc" as lined lists, you

    may ant to copy t"e entire memory location (t"e lined list) toanot"er obect

    - 9ou create a clone

    - called deep copy since you trace all memory locations t"at t"e obect is

    using.

    - 9ou "a%e to rite t"e necessary unction as a deep copy constructor (notcompiler pro%ided)

      Lin2edLi-t li-t$(li-t");

    list(  3 4 5

    list2  3 4 5node . /ead

    int size 0 3

    node . /ead

    int size 0 3

  • 8/20/2019 4.1 Advanced Classes

    19/56

    Deep Cop#Deep Cop# 6 7o, 6 7o,7o c"ange in t"e class deinition. Inly implementation is dierent

    - See t"is and net slide

    -  lso see linedlistetra class and demo (linedlistetra.cpp)

    cla-- Lin2edLi-t{ priate:

    node * !ead;int -ize;

     pulic: Lin2edLi-t (); Lin2edLi-t (con-t Lin2edLi-t ); //copy con-tructor3Lin2edLi-t (); //de-tructor

     oid printLi-t() con-t; oid addo4e5innin5(int n); oid deleteLi-t (); node * create?lone () con-t;//5enerate- t!e clone o' t!e li-t and return t!e clone@- !ead 

    };

  • 8/20/2019 4.1 Advanced Classes

    20/56

    Deep Cop#Deep Cop# 6 7o, 6 7o,Lin2edLi-t::Lin2edLi-t (con-t Lin2edLi-t copy){

    !ead = copy.create?lone();-ize = copy.-ize;

    }

    //5enerate- a clone o' t!e lin2ed li-t oAect y 5eneratin5 ne# copie- o'//eac! node and connectin5 t!em a- in t!e ori5inal.//Beturn- t!e !ead o' t!e clone li-t.node * Lin2edLi-t::create?lone () con-t

    { i' (!ead == NULL) //i' li-t i- emptyreturn NULL; //clone i- empty a- #ell

    //'ir-t 5enerate t!e 'ir-t clone node and connect to !ead o' clonenode * !ead?lone = ne# node (!ead78in'o, NULL);node * ptr = !ead78net; //-econd node in ori5.node * ptr?lone = !ead?lone; //to trac2 t!e clone li-t

      #!ile (ptr 6= NULL){ ptr?lone78net = ne# node (ptr78in'o, NULL); ptr = ptr78net; ptr?lone = ptr?lone78net;}return !ead?lone;

    }

    $et%s trace this

    on the board for

    a sample case

  • 8/20/2019 4.1 Advanced Classes

    21/56

    Deep Cop#Deep Cop# 6 7o, 6 7o, not"er eample using Lin2edCtrin5Cet class o Tapestry

      Lin2edCtrin5Cet li-t$(li-t");

    Lin2Ctrin5Cet::Lin2Ctrin5Cet (con-t Lin2Ctrin5Cet -et)

      :  myDir-t(ne# Node(E!eaderE,-et.clone())),  66same as0 my:irst L ne 7ode("eader,set.clone()))@

       myCize(-et.-ize())    see the color illustration below

    {  66 deep copy made in an initiali4er list no code let or "ere

    }

    - T"e nely created obect is calling a "elper unction called clone()

    - S"on in t"e net slide

     

    list2$m#8irst  3  4  5

    list($m#8irst 999$ 3 4 5

    :/eader;

  • 8/20/2019 4.1 Advanced Classes

    22/56

    Deep Cop#Deep Cop# 6 7o, 6 7o,Lin2Ctrin5Cet::Node * Lin2Ctrin5Cet::clone() con-t

    {  Node dummy (E!eaderE,0);

     Node * de-t = dummy;

     Node * temp = myDir-t78net;  #!ile (temp 6= NULL)

      { de-t78net = ne# Node(temp78in'o,NULL);  de-t= de-t78net;  temp = temp78net;  }  return dummy.net;

    }

    7ote "ere t"at t"e dummy node is a %ariable on t"e stac and t"us its scope ends"en e lea%e t"is unction. Hoe%er, due to t"e use in linstringset class, t"ereal dummy node is created outside  see pre%. slide0

      myDir-t(ne# Node(E!eaderE,-et.clone()))

  • 8/20/2019 4.1 Advanced Classes

    23/56

    +perator +verloading+perator +verloading

  • 8/20/2019 4.1 Advanced Classes

    24/56

    +verloading in C

  • 8/20/2019 4.1 Advanced Classes

    25/56

    1riting 8unction for +perators and1riting 8unction for +perators and

    +perator +verloading+perator +verloadingn !//, you can rite unctions or operators as ell.

    "en suc" an operator is used it" its operands, t"at unction is called.

    e ill see synta and eample in t"e coming slides.

    9ou can o%erload operators as you can o%erload unctions.

     ctually o%erloading or operators is ine%itable since t"e deined operators o!// already "a%e ot"er meanings

    !ompiler dierentiates among dierent meanings o t"e same operator using

    t"e types o t"e operands

  • 8/20/2019 4.1 Advanced Classes

    26/56

    Assignment +perator Assignment +perator Aet;s o%erload (mae it or or your on class) t"e assignment operator . 

    'sage# li-t$ = li-t";

     !ompiler interprets t"is as0  li-t$.operator=(li-t");

    ynta& for function header for operators

    Return_Type classname::operator Operator_Symbol  ( parameters)

    ynta& -&amples for function headers that define operators#

    con-t mycla--  mycla-- ::operator = (con-t mycla-- r!-)

    con-t lin2edli-t lin2edli-t::operator = (con-t lin2edli-t li-t")

    aution# 'se const/reference parameters instead of value parameters

    to avoid une&pected trics of shallow copy constructors and

    destructors

  • 8/20/2019 4.1 Advanced Classes

    27/56

    Implementation ofImplementation of Assignment +perator Assignment +perator Similar to t"e deep copy constructor, but t"e assignment operator is called

    to reinitiali4e an obect t"at "as already been constructed.

    Since t"e obect already eists, more booeeping is necessary.

    e ill see t"e implementation o assignment operator net, but beore t"ate ill see t!i- eyord.

  • 8/20/2019 4.1 Advanced Classes

    28/56

    2&

    t!i-t!i-"en you apply a member unction to an obect

      say calling member unction 'unc on obect oA

      oA.'unc()

    t"e program in%isibly eecutes

    t!i- = oA;

    beore t"e unction starts to eecute. T"us,

    – t!i- is a pointer to t"e obect on "ic" t"e unction is beingeecuted (in our eample oA).

      t"ereore, t"e unction can use *t!i- to reer to t"e current obecton "ic" t"e unction is eecuting

  • 8/20/2019 4.1 Advanced Classes

    29/56

    Implementation ofImplementation of Assignment +perator Assignment +perator  Prototype added to t"e class declaration (AinedAist*traIper.")

    cla-- Lin2edLi-t{ priate:

    node * !ead;int -ize;

     pulic: Lin2edLi-t (); Lin2edLi-t (con-t Lin2edLi-t ); //copy con-tructor3Lin2edLi-t (); //de-tructor oid printLi-t() con-t; oid addo4e5innin5(int n); oid deleteLi-t ();

     con-t Lin2edLi-t Lin2edLi-t::operator = (con-t Lin2edLi-t r!-);

     node * create?lone () con-t;};

  • 8/20/2019 4.1 Advanced Classes

    30/56

    Implementation ofImplementation of Assignment +perator Assignment +perator  Iperator unction is deined in t"e cpp ile (AinedAist*traIper.cpp)

    "en called as a = ;– a (t"e let "and side l"s) is t"e obect on "ic" t"e unction is running (i.e.

    *t!i-)

    –  is t"e parameter (i.e. r!-)

    con-t Lin2edLi-t Lin2edLi-t::operator = (con-t Lin2edLi-t r!-){

    i' (t!i- 6= r!-){

    deleteLi-t();!ead = r!-.create?lone();-ize = r!-.-ize;

    }return *t!i-;

    }

    If not self assignment -

    e need t"is guard since

    e clear t"e l"s beore

    t"e assignment. e

    donKt "a%e t"is, in case o

    sel assignment (e.g. a L

    a), t"e content is deleted

    beore copying.

    0elete the lhs

      ne data iscoming, old

    data s"ould go

    1ae

    deep

    copy and

    store in

    the lhs

    2ll assighments should

    return lhs due to

    cascaded assignments

    such as a 3 b 3 c

  • 8/20/2019 4.1 Advanced Classes

    31/56

    Demo -rogram =Lin>edListExtra+per$cpp?Demo -rogram =Lin>edListExtra+per$cpp?Lin2edLi-t li-t", li-t%;

    'or (int 2=0; 2 > ; 2){ li-t".addo4e5innin5(2");}cout >> Eli-t" contain-:InE;li-t".printLi-t();

    Lin2edLi-t li-t$(li-t"); cout >> Eli-t$ i- created 'rom li-t" u-in5 copy con-tructorInE;

    li-t% = li-t"; cout >> Eli-t" i- a--i5ned to li-t%InE;

    li-t".deleteLi-t(); cout >> Eli-t" i- deletedInE;

    cout >> EInli-t$ contain-:InE;li-t$.printLi-t();

    cout >> EInli-t% contain-:InE;li-t%.printLi-t();

    li-t".addo4e5innin5("00);li-t".addo4e5innin5(90); cout >> Eli-t" i- reinitialized and contain-:InE;

    li-t".printLi-t();

    li-t$ = li-t"; // -ame a- li-t$.operator = (li-t");cout >> Eli-t" i- a--i5ned to li-t$InE; cout >> Eli-t$ contain-:InE;li-t$.printLi-t();

    cout >> Eli-t$ i- a--i5ned to it-el'InE; cout >> Eli-t$ contain-:InE;li-t$ = li-t$; //try t!i- al-o a'ter deletin5 i' (t!i- 6= r!-) at operator de'initionli-t$.printLi-t();

    AetKs run t"is

    A i +A i t + t I l i iI l t ti i

  • 8/20/2019 4.1 Advanced Classes

    32/56

    Assignment +perator Assignment +perator @@ Implementation inImplementation in

    Lin>tringet classLin>tringet classconst AinStringSet>

    AinStringSet00operator L (const AinStringSet> set)  

    ?

      i (>set JL t"is) 66to pre%ent misbe"a%iour i aLa is used

      ? reclaim7odes(my:irst-Bnet)@ 66ree memory o l"s

      my:irst-Bnet L set.clone()@ 66copy r"s

      mySi4e L set.si4e()@

      E

      return Nt"is@ 66return l"s or situations "en

    66a L b L c@ is usedE 66"ic" is e

  • 8/20/2019 4.1 Advanced Classes

    33/56

    Lin>setdemo$cppLin>setdemo$cppint main()

    ?  AinStringSet a,b@

     

    a.insert(apple)@

      a.insert(c"erry)@

      cout OO a 0 @ Print(a)@ 66c"erry apple 2  b L a@

      cout OO b 0 @ Print(b)@ 66c"erry apple 2

      a.clear()@

      cout OO a 0 @ Print(a)@ 66

      cout OO b 0 @ Print(b)@ 66c"erry apple 2

    66as intended it" L, pro%ided by deepcopy in linstringset.cpp

      return @

    EC/ec> out Lin>tringet$/* cpp and t/is demo program

  • 8/20/2019 4.1 Advanced Classes

    34/56

    "apestr# C/p$ '$4"apestr# C/p$ '$4cloc>t$/ and cloc>t$cppcloc>t$/ and cloc>t$cpp

    e ill no loo at t"e Tapestry;s !locTime class or0

       more operator o%erloading

       class design

    Ho to design a cloc time classF  to represent a cloc time obect0 1+05+0

  • 8/20/2019 4.1 Advanced Classes

    35/56

    Cloc>"ime ClassCloc>"ime Classclass !locTime

    ?

      public0  locTime()4

      locTime(int secs, int mins, int hours)4

     

    int 5ours() const4 returns 6 hours

      int 1inutes() const4 returns 6 minutes

      int econds() const4 returns 6 seconds

    string tostring() const4 converts to string

     

    bool * ct) const@ 66 true i LL ct

      bool Aess (const !locTime> ct) const@ 66 true i O ct

      const !locTime > operator /L (const !locTime > ct)@

     

    pri%ate0void 7ormali8e()4 66normali4ed suc" t"at O ' secs, O ' min

    int myeconds4 constrained# 9/:;

    int my1inutes4 constrained# 9/:;

      int my5ours4

    E@

  • 8/20/2019 4.1 Advanced Classes

    36/56

    Cloc>"ime ClassCloc>"ime Class

    !locTime00!locTime (int secs, int mins, int "ours)

      0 mySeconds(secs), myQinutes(mins), myHours("ours)  66 postcondition0 all data ields initiali4ed

    ?

      7ormali4e()@

    E

    %oid !locTime007ormali4e()

    ?

      myQinutes /L ...

      mySeconds ... 

    myHours /L ...

      myQinutes ...

    E

  • 8/20/2019 4.1 Advanced Classes

    37/56

    Cloc>"ime ClassCloc>"ime Class!locTime00!locTime (int secs, int mins, int "ours)

      0 mySeconds(secs), myQinutes(mins), myHours("ours)  66 postcondition0 all data ields initiali4ed

    ?

      7ormali4e()@

    E

    %oid !locTime007ormali4e()

    ?

      myQinutes /L mySeconds6'@ 66 o%erlo rom secs to myQinutes

      mySeconds RL '@ 66 no beteen and 5+

     

    myHours /L myQinutes6'@ 66 o%erlo rom myQinutes to myHours

      myQinutes RL '@ 66 no beteen and 5+

    E

  • 8/20/2019 4.1 Advanced Classes

    38/56

    7elper 8unctions of t/e Cloc>"ime class7elper 8unctions of t/e Cloc>"ime class

    T"ese ill be used in operator o%erloading. T"eyimplement t"e straig"torard meaning (mae sureyou understand)0

    bool !locTime00* c) const66usage0 c1.*

  • 8/20/2019 4.1 Advanced Classes

    39/56

    7elper 8unctions of t/e Cloc>"ime class7elper 8unctions of t/e Cloc>"ime classT"ese ill be used in operator o%erloading. T"ey implement t"e

    straig"torard meaning (mae sure you understand)0

    bool !locTime00Aess (const !locTime> c) const

    66 postcondition0 returns true i t"is obect;s time O c

    ?

      return ( Hours() O c.Hours() )

      ( ( Hours() LL c.Hours() ) >>

    ( ( Qinutes() O c.Qinutes() )

      ( ( Qinutes() LL c.Qinutes() ) >> ( Seconds() O c.Seconds() ) )

      )

      )@

    E

  • 8/20/2019 4.1 Advanced Classes

    40/56

    +verloading +perators+verloading +perators

    7o let;s o%erload t"e operator BL. :irst notice t"at e s"ould be able to use t"eCBLC operator it" cloctimes in 3 ays0

    !locTime c1, c2@

    i ( c1 BL c2)

    i ( c1 BL 1) (let t"is mean Cc1 is more t"an or e

  • 8/20/2019 4.1 Advanced Classes

    41/56

    +verloading 6complete case for 0+verloading 6complete case for 0  AetKs detail a bit

     !locTime c1, c2@

    i ( c1 BL c2) calls c1.operatorBL(c2) bool locTime##operator return * ( $ess(rhs) )4 uses the helper function $ess() of c?.

    @

    i ( c1 BL 1) calls c1.operatorBL(1) 0 let t"is mean is t"e time more t"an 1 "r

    bool locTime##operator return ( 5ours() return ( my5ours =(c1) since 1 is a constant, so t"is %ersiono t"e operatorBL must be a ree unction

     

  • 8/20/2019 4.1 Advanced Classes

    42/56

    +verloading 6complete case for 0+verloading 6complete case for 0

    i ( c1 BL c2) calls c1.operatorBL(c2) bool locTime##operator return * ( $ess(rhs) )4 uses the helper function $ess() of c?.

    @

    i ( c1 BL 1) calls c1.operatorBL(1) 0 let t"is mean is t"e time more t"an 1 "r

    bool locTime##operator return ( 5ours() return ( my5ours =(c1) since 1 is a constant, so t"is %ersion

    o t"e operatorBL must be a ree unction

    bool operator locTime temp(9, 9, lhs)4

      return temp

  • 8/20/2019 4.1 Advanced Classes

    43/56

    +perator ct)

    66 postcondition0 add ct, return normali4ed result

    ?

    E

  • 8/20/2019 4.1 Advanced Classes

    44/56

    +perator ct)66 postcondition0 add ct, return normali4ed result

    ?

      mySeconds /L ct.mySeconds@

      myQinutes /L ct.myQinutes@

      myHours /L ct.myHours@

      7ormali4e()@

      return Nt"is@

    E

  • 8/20/2019 4.1 Advanced Classes

    45/56

    +perator

  • 8/20/2019 4.1 Advanced Classes

    46/56

    cloc>t$cpp 6 ot/er overloaded operatorscloc>t$cpp 6 ot/er overloaded operatorsn cloct cpp, only some orms o t"e o%erloaded operators are pro%ided  (apparently

    t"ey did not see a good use comparing cloctime obects to constants etc.) and most

    are declared as ree unctions0  ostream = operator AA  (ostream = os, const locTime = ct)4

      locTime operator B  (const locTime = lhs, const locTime = rhs)4

      bool operator 33  (const locTime= lhs, const locTime= rhs)4

      bool operator *3  (const locTime= lhs, const locTime= rhs)4

      bool operator A  (const locTime= lhs, const locTime= rhs)4  bool operator

  • 8/20/2019 4.1 Advanced Classes

    47/56

    +perator l"s, const !locTime > r"s)

    66 postcondition0 return l"s / r"s (normali4ed or myQinutes, mySeconds)

    ?

      ..............................  ..............................

      .............................

    E

    +perator

  • 8/20/2019 4.1 Advanced Classes

    48/56

    +perator r"s)

    66 postcondition0 return l"s / r"s (normali4ed or myQinutes, mySeconds)?

      !locTime result(l"s)@ 66uses t"e deault (compiler generated) copy constructor 

      result /L r"s@ 66uses t"e pre%iously deined operator/L

      return result@

    E

    "y is t"e return type ust !locTime but not a reerence as in L and /LF

      e return result, "ic" is a local obect. eturning reerence o a local obect6%ariable is %ery

    problematic since t"e scope ends ater t"e unction. n t"e current orm o !locTime class t"is may

    not cause a problem but i e "ad a destructor or !locTime, t"at ould be a problem. AetKs simulate

    t"is case by "a%ing a destructor t"at initiali4es pri%ate data members.

    "y did e need resultF "y not simply "a%e only return l!-= r!-F

      Mecause you cannot c"ange t"e %alue o a const reerence parameter, compiler does not allo t"is.

    "at about using %alue parameters or l"s and r"sF

      T"is time you could ust "a%e return l!-= r!-@ in t"e unction body@ but causes unnecessarycopy

    8 i d f i8 i d f i

  • 8/20/2019 4.1 Advanced Classes

    49/56

    4'

    8riend functions8riend functions  riend unction is used for accessing the non/public members of a class.

      riend unction is an ordinary (ree) unction or a member unction o anot"erclass.

    T"e riend unction is ritten as any ot"er normal unction.

    Hoe%er, you "a%e to add a prototype or t"e unction in t"e class declaration by

    putting t"e eyord friend at t"e beginning  =se friend eyord in t"e prototype only, not in t"e unction deinition.

    t is possible to declare a unction as riend in any number o classes.

    "en a class is declared as a riend, t"e riend class "as access to t"e pri%ate data

    o t"e class t"at made t"is a riend.

      ill see riend classes later 

    T"e unction is in%oed it"out t"e use o an obect0 obects are passed to it as

    arguments.

  • 8/20/2019 4.1 Advanced Classes

    50/56

    An Example 8riend 8unctionAn Example 8riend 8unctionAetKs o%erload / operator (to operands but t"e irst one is an integer, second

    one is a cloc)

    ?loc2ime operator (int l!-, con-t ?loc2ime r!-)

     dds l"s "ours to r"s and returns t"e ne cloc %alue.

    AetKs implement t"is as a ree unction. ctually !locTime class "as enoug"

    accessors or implementation, but letKs do it by accessing pri%ate datamembers. e add t"e olloing unction to cloct.cpp

    ?loc2ime operator (int l!-, con-t ?loc2ime r!-){

    ?loc2ime temp (r!-. myCecond-, r!-. myJinute-, r!-. myour-  l!-);

    return temp;}

    Since e use pri%ate data members o t"e class, t"is unction s"ould be a

    riend unction. To do so also add t"e olloing prototype to cloctime."

    it"in t"e class declaration

    'riend ?loc2ime operator (int l!-, con-t ?loc2ime r!-);

  • 8/20/2019 4.1 Advanced Classes

    51/56

    +verloading IB+ operators+verloading IB+ operatorsostream > operator OO (ostream > os, const !locTime > ct)

    66 postcondition0 inserts ct onto os, returns os66 ormat is "0m0s 

    ?

      os OO ct.tostring()@

      return os@

    E

    string !locTime00tostring() const

    ?

      ostringstream os@ 66to use a string as a stream

      os.ill(KK)@ 66unused spaces on t"e let ill it" s

      os OO Hours() OO 0 OO set(2) OO Qinutes() OO 0  OO set(2) OO Seconds()@ ?#9;#:; 

    return os.str()@

    E

  • 8/20/2019 4.1 Advanced Classes

    52/56

    +verloading IB+ operators+verloading IB+ operators

    ostream > operator OO (ostream > os, const !locTime > ct)

    66 postcondition0 inserts ct onto os, returns os66 ormat is "0m0s 

    ?

      os OO ct.tostring()@

      return os@

    E

    operator OO cannot be a member unction (in general)

      cout OO c1@

    ostream (output streams) "as to be passed as reerence

      Since t"e ostream is modiied "en you put somet"ing on t"e stream

    operator OO must return os

      in case e use0 cout OO c1 OO c2@ since OO is let-to-rig"t associati%e, t"eresult o cout OO c1 must be cout (parameter os).

  • 8/20/2019 4.1 Advanced Classes

    53/56

    +t/er overloaded operators+t/er overloaded operatorsbool operator LL (const !locTime> l"s, const !locTime> r"s)

    ?  return l"s.* r"s)?

      return J (l"s LL r"s)@

    E

    ... Lets see all of t/ese in cloc>t$/ and cloc>t$cpp

  • 8/20/2019 4.1 Advanced Classes

    54/56

    1/at /appened to operator 0 1/at /appened to operator 0 Ha%e you reali4ed t"at !locTime class do not "a%e operator L F

      7eit"er member nor ree unction

    Mut e can use assignment operator (see usecloc.cpp)

    t"ere is no L operator implemented in o%erloaded operators compiler

    pro%ides a deault implementation automatically

    8eault assignment operator maes s"allo copy as in deault copy

    constructor 

      Inly pri%ate data members are copied

    you are "appy it" t"at, t"en you do not need to rite a unction or L

      T"is is acceptable or !locTime class since it does not use any

    dynamic memory rom "eap

    Using in return valuesUsing in return values

  • 8/20/2019 4.1 Advanced Classes

    55/56

    Using in return valuesUsing in return values=reference return t#pe? 6=reference return t#pe? 6 7orton pp$ 2&)% 2&37orton pp$ 2&)% 2&3

    Sometimes e use reference return %alues suc" as

    con-t ClassName  FunctionName (Parameters)

    ClassName  FunctionName (Parameters)

      :or eample, operator = or !locTime class and operator = AinedAist class,Iperator >> o !locTime class

    "at is t"e dierence beteen t"ese and using ust t"e !lass7ame as

    t"e return type (%alue return)F

    ClassName FunctionName (Parameters)

    =sing ust t"e class name (%alue return) generates a copy o t"e return%alue "en returning

      T"is in%oes copy constructor (user deined or i it does not eist deault one)

      T"is is risy i not implemented (s"allo copy problem)

       nd it is ineient to call t"e copy constructor or t"is purpose

    55

    Using in return valuesUsing in return values

  • 8/20/2019 4.1 Advanced Classes

    56/56

    Using in return valuesUsing in return values

    =reference return t#pe?=reference return t#pe? Sometimes t"e obect to be returned "as already been deined outside

    o t"e unction (or dynamically allocated it"in t"e unction)

      n suc" a case, e can directly return t"at obect it"out a copy

    operation

    T"is is called reference return

    T"e mec"anisms it" & does t"is.  Me careul, do not return a local %ariable using t"is met"od

    Aocal %ariable gets lost ater t"e unction

    Probably your program cras"es

    "at is t"e eect o using const "ereF

      7ot muc", a %ery deensi%e programming tec"ni