CPP_v1.1 OOP

Embed Size (px)

Citation preview

  • 7/23/2019 CPP_v1.1 OOP

    1/439

    2013-2015 Margit ANTAL

    C++ Object-Oriented Programming

    CPP

  • 7/23/2019 CPP_v1.1 OOP

    2/439

    2013-2015 Margit ANTAL

    C++ - Object-Oriented Programming

    Course content

    Introduction to C++

    Object-oriented programming

    Generic programming and the STL

    Object-oriented design

  • 7/23/2019 CPP_v1.1 OOP

    3/439

    2013-2015 Margit ANTAL

    C++ - Object-Oriented Programming

    References M Gregoire!Professional C++! "rd edition! #ohn $i%e& ' Sons! 2014

    S Lippman! # Lajoie! ( ) Moo! C++ Primer! *thedition! ddison

    $es%e&! ! 2013 S Prata! C++ Primer Plus! ,thedition! ddison $es%e&! 2012

    Josuttis! The C++ standard library. a tutorial and reference.Pearson)ducation 2012.

    Williams! C++ Concurrenc& in ction.Practica% Mu%tithreading

    Green/ich! CT. Manning 2012.

  • 7/23/2019 CPP_v1.1 OOP

    4/439

    2013-2015 Margit ANTAL

    Modu%e 0

    Introduction to C++

  • 7/23/2019 CPP_v1.1 OOP

    5/439

    2013-2015 Margit ANTAL

    Introduction to C++

    Content

    1istor& and e2o%ution

    O2er2ie/ of the 3e& features

    e/ bui%t-in t&pes Scope and namespaces

    )numerations

    4&namic memor&. newand delete

    )rror hand%ing /ith e5ceptions References

    The const modifier

  • 7/23/2019 CPP_v1.1 OOP

    6/439

    2013-2015 Margit ANTAL

    Introduction to C++

    1istor& and e2o%ution

    Creator. (jarne Stroustrup067"

    Standards.

    The first C++ standard

    0667 8C++679

    :;;" 8C++;"9 < technica% corrigendum < minor bug fi5es

    :;;=8TR09 < %ibrar& e5tensions

    The second C++ standard :;00 8C++009 < significant impro2ements in %anguage and %ibrar&

    http://www.stroustrup.com/http://www.stroustrup.com/
  • 7/23/2019 CPP_v1.1 OOP

    7/439

    2013-2015 Margit ANTAL

    Introduction to C++

    Phi%osoph&

    Statica%%& t&ped

    Genera% purpose

    )fficient

    Supports mu%tip%e programming st&%es.

    Procedura% programming

    Object-oriented programming Generic programming

  • 7/23/2019 CPP_v1.1 OOP

    8/439

    2013-2015 Margit ANTAL

    Introduction to C++

    Standard %ibrar&

    C++ standard %ibrar& > C standard %ibrar& + STL8Standard Temp%ate Librar&9

    STL < designed b&%e5ander Stepano2! pro2ides. Containers. list, vector, set, map

    Iterators

    %gorithms. search, sort,

    http://en.wikipedia.org/wiki/Alexander_Stepanovhttp://en.wikipedia.org/wiki/Alexander_Stepanov
  • 7/23/2019 CPP_v1.1 OOP

    9/439

    2013-2015 Margit ANTAL

    Introduction to C++

    Portabi%it&

    Recompi%ation /ithout ma3ing changes in thesource code means portabi%it&

    1ard/are specific programs are usua%%& notportab%e

  • 7/23/2019 CPP_v1.1 OOP

    10/439

    2013-2015 Margit ANTAL

    Introduction to C++

    Creating a program

    ?se a te5t editor to /rite a program and sa2e it in afi%e @ source code

    Compi%e the source code 8compi%er is a programthat trans%ates the source code to machine%anguage9 @ object code

    Lin3 the object code /ith additiona% code 8libraries9

    @ executable code

  • 7/23/2019 CPP_v1.1 OOP

    11/439

    2013-2015 Margit ANTAL

    Introduction to C++

    Creating a program 8using G? C++ compi%er! ?ni59

    Source code. hello.cpp

    Compi%e. g++ -chello.cpp

    Output. hello.o 8object code9

    Compi%e + Lin3.g++ hello.cpp

    Output.a.out 8e5ecutab%e code9

    C++ :;00. g++ hello.cpp -std=c++0x

  • 7/23/2019 CPP_v1.1 OOP

    12/439

    2013-2015 Margit ANTAL

    Introductionto C++

    The first C++ program

    //hello.cpp

    #include using namespace std;

    int main(){cout

  • 7/23/2019 CPP_v1.1 OOP

    13/439

    2013-2015 Margit ANTAL

    Introduction to C++

    (ui%ding a C++ program. " steps

    preprocessor 8%ine starting /ith B9

    compi%er

    %in3er

  • 7/23/2019 CPP_v1.1 OOP

    14/439

    2013-2015 Margit ANTAL

    Introduction to C++

    Most common preprocessor directi2es

    #include %&ile'

    the specified &ileis inserted into the code

    #de&ine %e' %value'

    e2er& occurrence of the specified eis rep%aced/ith the specified value

    #i&nde& %e' #endi& code b%oc3 is conditiona%%& inc%uded

  • 7/23/2019 CPP_v1.1 OOP

    15/439

    2013-2015 Margit ANTAL

    Introduction to C++

    1eader fi%es

    C++ header

    #include

    C header

    #include

    ?ser defined header

    #include *mheader.h*

  • 7/23/2019 CPP_v1.1 OOP

    16/439

    2013-2015 Margit ANTAL

    Introduction to C++

    2oid mu%tip%e inc%udes//myheader.h

    #i&nde& !--01!#de&ine !--01!

    // the contents

    #endi&

  • 7/23/2019 CPP_v1.1 OOP

    17/439

    2013-2015 Margit ANTAL

    Introduction to C++

    The main()function

    int main(){

    or

    int main( int argc, char2 argv%' ){

    The numberof arguments

    The argumentsResu%t status

  • 7/23/2019 CPP_v1.1 OOP

    18/439

    2013-2015 Margit ANTAL

    Introduction to C++

    IAO Streams

    cout$ standard output

    cout d;

    )nd of %ine

  • 7/23/2019 CPP_v1.1 OOP

    19/439

    2013-2015 Margit ANTAL

    Introduction to C++

    amespaces

    a2oid naming conf%icts//my1.hnamespace mspace5{

    void &oo();

    //my2.hnamespace mspace6{

    void &oo();

    //my1.cpp#include m5.hnamespace mspace5{ void &oo(){

    cout

  • 7/23/2019 CPP_v1.1 OOP

    20/439

    2013-2015 Margit ANTAL

    Introduction to C++

    Dariab%es

    can be dec%ared a%most an&/here in &our code

    dou4le d; //uninitiali8ed

    int i 9 5"; //initiali8ed

  • 7/23/2019 CPP_v1.1 OOP

    21/439

    2013-2015 Margit ANTAL

    Introduction to C++

    Dariab%e t&pes short, int, long : range depends on compi%er! but usua%%& 6, ,

    4tes

    long long8C++009 < range depends on compi%er < usua%%& 4tes

    &loat, dou4le, long dou4le

    4ool

    char, char5=1t8C++009, char61t8C++009, wchar1t

    auto 8C++009 < the compi%er decides the t&pe automatica%%& 8auto i9?;9

    decltpe(e@pr)8C++009int i95";

    decltpe(i) A 9 6"; AA A/i%% be int

  • 7/23/2019 CPP_v1.1 OOP

    22/439

    2013-2015 Margit ANTAL

    Introduction to C++

    Dariab%e t&pes#include using namespace std;

    int main(int argc, char22 argv) {

    cout

  • 7/23/2019 CPP_v1.1 OOP

    23/439

    2013-2015 Margit ANTAL

    Introduction to C++

    C++;5AC++00 Support in GCC

    https.AAgccgnuorgAprojectsAc55;5htm%

    On%ine C++ compi%ers.

    http.AAisocpporgAb%ogA:;0"A;0Aon%ine-c-compi%ers

    https://gcc.gnu.org/projects/cxx0x.htmlhttp://isocpp.org/blog/2013/01/online-c-compilershttp://isocpp.org/blog/2013/01/online-c-compilershttps://gcc.gnu.org/projects/cxx0x.html
  • 7/23/2019 CPP_v1.1 OOP

    24/439

    2013-2015 Margit ANTAL

    Introduction to C++

    C enumerations 8not type-safe9

    a%/a&s interpreted as integers @

    &ou can compare enumeration 2a%ues from comp%ete%&

    different t&pesenum Bruit{ apple, straw4err, melon;

    enum Cegeta4le{ tomato, cucum4er, onion;

    void &oo(){ i&(

    tomato == apple){

    cout

  • 7/23/2019 CPP_v1.1 OOP

    25/439

    2013-2015 Margit ANTAL

    Introduction to C++

    C++ enumerations 8type-safe9

    enum classar { Dnde&ined, Eow, edium, !igh;

    ar mar( int value ){ switch( value ){ case 5$ case6$ return ar$$Eow; case $ case$ return ar$$edium; case F$ return ar$$!igh; de&ault$

    return ar$$Dnde&ined;

  • 7/23/2019 CPP_v1.1 OOP

    26/439

    2013-2015 Margit ANTAL

    Introduction to C++

    Range-based&or%oopint elements%'9{5,6,,,F;

    &or( autoG e$ elements){cout

  • 7/23/2019 CPP_v1.1 OOP

    27/439

    2013-2015 Margit ANTAL

    Introduction to C++

    The std$$arra

    rep%acement for the standard C-st&%e arra&

    cannot gro/ or shrin3 at run time

    #include #include using namespace std;

    int main() { arra arr 9 {5", 6", ", ", F"; cout

  • 7/23/2019 CPP_v1.1 OOP

    28/439

    2013-2015 Margit ANTAL

    rtarra&

    Stac3 1eap

    Introduction to C++

    Pointers and d&namic memor& compi%e time arra& int ctarra% '; //allocated on stack

    run time arra& int 2 rtarra 9 newint% '; //allocated on heap

  • 7/23/2019 CPP_v1.1 OOP

    29/439

    2013-2015 Margit ANTAL

    Introduction to C++

    4&namic memor& management

    a%%ocation

    int 2 @ 9 newint;

    int 2 t 9 newint [ ];

    de%etion

    delete@;

    delete []t;

  • 7/23/2019 CPP_v1.1 OOP

    30/439

    2013-2015 Margit ANTAL

    Introduction to C++

    Strings

    HIstle strings.

    arra& of characters

    J7"Jterminated functions pro2ided in

    H++ string

    described in

    string &irstKame 9 *Lohn*; string lastKame 9 *Mmith*;

    string name 9 &irstKame+ * *+ lastKame; cout

  • 7/23/2019 CPP_v1.1 OOP

    31/439

    2013-2015 Margit ANTAL

    Introduction to C++

    References

    reference defines an alternative name(aliasfor an object

    reference must be initiali!ed.

    4efining a reference >bindinga reference to its initia%iEer

    int i 9 5";

    int Gri 9 i; //! r" re#ers to $"s another name #or% "

    int Gri5; //&''': a re#erence must (e "n"t"al")ed

  • 7/23/2019 CPP_v1.1 OOP

    32/439

    2013-2015 Margit ANTAL

    Introduction to C++

    Operations on references

    the operation is a%/a&s performed on the referred object

    int "9 5";

    int *r"9 i;

    ++r";

    cout

  • 7/23/2019 CPP_v1.1 OOP

    33/439

    2013-2015 Margit ANTAL

    Introduction to C++

    References as function parameters

    to permitpass-by-reference"

    a%%o/ the function to modif& the 2a%ue of the parameter

    a2oid copiesvoid inc(int *value){

    value++;

    usage:int @ 9 5";inc( @ );

    4ool isMhorter(const string Gs5,const string Gs6)

    {return s5.si8e() < s6.si8e();

    usage:string str5 9*apple*;string str6 9*nut*;cout

  • 7/23/2019 CPP_v1.1 OOP

    34/439

    2013-2015 Margit ANTAL

    Introduction to C++

    )5ceptions

    )5ception > une5pected situation

    )5ception hand%ing > a mechanism for dea%ing /ith prob%ems

    thro#ingan e5ception < detecting an une5pected situation

    catchingan e5ception < ta3ing appropriate action

  • 7/23/2019 CPP_v1.1 OOP

    35/439

    2013-2015 Margit ANTAL

    Introduction to C++

    )5ceptions

    #include #includestdexcept,using namespace std;

    dou4le divide( dou4le m, dou4le n){ i&( n 99 " ){ throwstd$$except"on(); else{ return m/n;

    int main() { try{ cout

  • 7/23/2019 CPP_v1.1 OOP

    36/439

    2013-2015 Margit ANTAL

    Introduction to C++

    The constmodifier

    4efining constants

    Protecting a parameter

    constint K 95";

    int t% K ';

    constint K 95";

    int t% K ';

    void sa!ello( conststringG who){ cout

  • 7/23/2019 CPP_v1.1 OOP

    37/439

    2013-2015 Margit ANTAL

    Introduction to C++

    ?sing the standard %ibrar&

    constint K 95";

    int t% K ';

    #include #include #include using namespace std;

    int main() { ectorstring,&ruits 9 {*apple*,*melon*; &ruits.push(ack(*pear*); &ruits.push(ack(*nut*); // terate oer the elements "n the ector and pr"nt them &or (auto"t=&ruits.c(eg"n$%; "t =&ruits.cend$%; ++"t) { cout

  • 7/23/2019 CPP_v1.1 OOP

    38/439

    2013-2015 Margit ANTAL

    Introduction to C++

    Programming task:

    $rite a program that reads one-/ord strings from thestandard input! stores them and fina%%& prints them on thestandard output

    Sort the container before printing

    use the sorta%gorithm

    #includealgor"thm,...vector &ruits;...sort(&ruits.4egin(),&ruits.end());

  • 7/23/2019 CPP_v1.1 OOP

    39/439

    2013-2015 Margit ANTAL

    Modu%e :

    Object-Oriented Programming

    C%asses and Objects

  • 7/23/2019 CPP_v1.1 OOP

    40/439

    2013-2015 Margit ANTAL

    Object-Oriented Programming 8OOP9

    Content

    C%asses and Objects

    d2anced C%ass Features

    Operator o2er%oading Object Re%ationships

    bstraction

  • 7/23/2019 CPP_v1.1 OOP

    41/439

    2013-2015 Margit ANTAL

    OOP. C%asses and Objects

    Content

    Members of the c%ass ccess %e2e%s )ncapsu%ation

    C%ass. interface + imp%ementation

    Constructors and destructors constmember functions

    Constructor initia%iEer

    Cop& constructor

    Objects %ifec&c%e

  • 7/23/2019 CPP_v1.1 OOP

    42/439

    2013-2015 Margit ANTAL

    OOP. C%asses and objects

    C%ass > T&pe 8 4ata + Operations9 Members of the c%ass

    Data:

    data members 8properties9

    Operations:

    methods 8beha2iors9

    )ach member is associated /ith an access level.

    private -

    pu4lic +

    protected 3

  • 7/23/2019 CPP_v1.1 OOP

    43/439

    2013-2015 Margit ANTAL

    OOP. C%asses and objects

    Object > Instance of a c%ass

    n emp%o&ee object. -mploee emp;

    Propertiesare the characteristics that describe an

    object $hat ma%es this object different&

    id, &irstKame, lastKame, salar, hired

    e!aviorsans/er the Huestion.

    $hat can #e do to this object& hire(), &ire(), displa(),getand setdata

    members

  • 7/23/2019 CPP_v1.1 OOP

    44/439

    2013-2015 Margit ANTAL

    OOP. C%asses and objects

    )ncapsu%ation an object encapsu%ates data and functionality

    4ata

    Functiona%it&

    class "#P$%

    $mplo&ee

    - mId. int

    - mFi rstam e. strin g

    - mL astam e. string

    - mSa% ar&. int

    - b1ired. boo%

    + )mp%o&ee89+ disp%a&89 . 2oid Hue r&J

    + hire89 . 2oid

    + fire89 . 2oid

    + setFi rstam e8strin g9 . 2oi d

    + setLa stame 8string9 . 2oid

    + setId8int9 . 2oid

    + setSa% ar&8int9 . 2oid

    + getFirstame 89 . string Hue r&J

    + getLa stame89 . string Huer&J

    + getSa %ar&89 . int Huer&J

    + getIs1ired89 . boo % Huer&J

    + getId89 . in t Huer&J

  • 7/23/2019 CPP_v1.1 OOP

    45/439

    2013-2015 Margit ANTAL

    OOP. C%asses and objects

    C%ass creation

    c%ass 'eclaration- interface

    -mploee.h

    c%ass 'e(inition< implementation -mploee.cpp

    OOP. C%asses and objects

  • 7/23/2019 CPP_v1.1 OOP

    46/439

    2013-2015 Margit ANTAL

    OOP. C%asses and objects

    class&mployee4pu(l"c: -mploee(); void displa() const5 void hire(); void &ire(); // 6etters and setters void setBirstKame( string inBirstKame ); void setEastKame ( string inEastKame );

    void setNd( int inNd ); void setMalar( int inMalar ); string getBirstKame() const5 string getEastKame() const5 int getMalar() const5 4ool getNs!ired() const5

    int getNd()const5pr"ate: int mNd;

    string mBirstKame; string mEastKame; int mMalar; 4ool 4!ired;75

    Methods dec%aration

    4ata members

    )mp%o&eeh

  • 7/23/2019 CPP_v1.1 OOP

    47/439

    2013-2015 Margit ANTAL

    OOP. C%asses and objects

    The Constructor and the objects state The state o( an o)*ectis defined b& its data members

    Theconstructoris responsib%e for the initial stateof the object

    -mploee $$ &mployee$%:mNd(I5),

    mBirstKame(**),mEastKame(**),mMalar("),4!ired(&alse)4

    7

    -mploee $$ &mployee$%{ mNd 9 I5;

    mBirstKame9**;

    mEastKame9**;mMalar 9";4!ired 9 &alse;

    Members are initia%iEedthrough theconstructor initia%iEer %ist

    Members are assigned

    Only constructors can use

    thisinitializer-listsyntax!!!

  • 7/23/2019 CPP_v1.1 OOP

    48/439

    2013-2015 Margit ANTAL

    OOP. C%asses and objects

    Constructors

    responsibility"data members initia%iEation of a c%ass object

    in2o3ed automatica%%& for each object

    ha2e the same nameas the c%ass ha2e no return type

    a c%ass can ha2e multiple constructors8function overloa'ing9

    ma& not be dec%ared as const

    constructors can /rite to const objects

  • 7/23/2019 CPP_v1.1 OOP

    49/439

    2013-2015 Margit ANTAL

    OOP. C%asses and objects

    4efining a member function

    )mp%o&eecpp

    const mem)er (unctioncannot change the objectsstate! can be in2o3ed on const objects

    void -mploee$$h"re$%{ 4!ired 9 true;

    string -mploee$$get8"rst9ame$%const{

    return mBirstKame;

  • 7/23/2019 CPP_v1.1 OOP

    50/439

    2013-2015 Margit ANTAL

    OOP. C%asses and objects

    4efining a member function

    void -mploee$$d"splay$% const { cout

  • 7/23/2019 CPP_v1.1 OOP

    51/439

    2013-2015 Margit ANTAL

    OOP. C%asses and objects

    Test)mp%o&eecpp

    ?sing constmember functionsvoid &oo( const-mploeeG e){ e.displa(); // !.displa() is a const mem4er &unction e.&ire(); // &'''.&ire() is not a const mem4er &unction

    int main() { -mploee emp; emp.setBirstKame(*0o4ert*); emp.setEastKame(*Plac*); emp.setNd(5); emp.setMalar(5"""); emp.hire(); emp.displa();

    #oo$ emp %5 return ";

    OOP. C%asses and objects

  • 7/23/2019 CPP_v1.1 OOP

    52/439

    2013-2015 Margit ANTAL

    OOP. C%asses and objects

    3"#nde# &&mployee.h>

    &mployee::-mploee() $mNd(I5),

    mBirstKame(**),mEastKame(**),mMalar("),4!ired(&alse){

    string &mployee::getBirstKame() const{ return mBirstKame;// ...

    Imp%ementation. $mplo&ee.cpp

  • 7/23/2019 CPP_v1.1 OOP

    53/439

    2013-2015 Margit ANTAL

    OOP. C%asses and objects

    Object %ife c&c%es.

    creation

    assignment

    destruction

  • 7/23/2019 CPP_v1.1 OOP

    54/439

    2013-2015 Margit ANTAL

    OOP. C%asses and objects

    Object creation.

    /hen an object is created! one of itsconstructors is e5ecuted!

    a%% its embeddedobjectsare a%so created

    int main() { -mploee emp; emp.displa();

    -mploee ?demp9 new -mploee(); dempI>displa(); // .. delete demp; return ";

    objects%ifec&c%e

  • 7/23/2019 CPP_v1.1 OOP

    55/439

    2013-2015 Margit ANTAL

    OOP. C%asses and objects

    Object creation < constructors.

    default constructor8;-argument constructor9

    /hen &ou need

    -mploee emploees% 5" ';

    vector emps;

    -mploee $$ &mployee$%$ mNd(I5), mBirstKame(**),mEastKame(**), mMalar("), 4!ired(&alse){

    -mploee $$ &mployee$%{

    memor& a%%ocation constructor ca%% on

    each a%%ocated object

  • 7/23/2019 CPP_v1.1 OOP

    56/439

    2013-2015 Margit ANTAL

    OOP. C%asses and objects

    Object creation < constructors.

    Compiler-generated default constructor

    if a c%ass does not specifyan& constructors! thecompiler #ill generate

    one that does not ta3e an& arguments

    class@alue{pu4lic$

    void setCalue( dou4le inCalue);dou4le getCalue() const;private$

    dou4le value;;

  • 7/23/2019 CPP_v1.1 OOP

    57/439

    2013-2015 Margit ANTAL

    OOP. C%asses and objects

    Constructor initia%iEer

    class onst'e#4pu(l"c: Honst0e&( int );pr"ate: int mN;

    const int mHi; intG m0i;75

    onst'e#:$Honst0e&( int inN ){ mN 9 inN; //QR mHi 9 inN; //&''': cannot ass"gn to a const m0i 9 inN; //&''': un"n"t"al")ed re#erence mem(er

    onst'e#:$Honst0e&( int inN )$ mN( inN ), mHi( inN ), m0i( inN ){

    ctor initiali!er

  • 7/23/2019 CPP_v1.1 OOP

    58/439

    2013-2015 Margit ANTAL

    OOP. C%asses and objects

    Constructor initia%iEer

    data t&pes that must be initia%iEed in a ctor-initia%iEer

    constdata members

    reference data members object data members ha2ing no defau%t

    constructor

    superc%asses /ithout defau%t constructor

  • 7/23/2019 CPP_v1.1 OOP

    59/439

    2013-2015 Margit ANTAL

    OOP. C%asses and objects

    non-defaultConstructor

    -mploee $$ &mployee$ "nt "ndA str"ng "n8"rst9ameAstr"ng "n;ast9ameA"nt "nBalaryA "nt "n"red%$

    mNd(inNd), mBirstKame(inBirstKame),

    mEastKame(inEastKame), mMalar(inMalar),4!ired(in!ired4

    7

  • 7/23/2019 CPP_v1.1 OOP

    60/439

    2013-2015 Margit ANTAL

    OOP. C%asses and objects

    Copy Constructor

    ca%%ed in one of the fo%%o/ing cases.

    -mploee emp5(5, *0o4ert*, *Plac*, """, true);

    -mploee emp6( emp5 ); //copIconstructor called

    -mploee emp 9 emp6; //copIconstructor called

    void &oo( -mploee emp );

    if &ou dont define a cop&-constructor e5p%icit%&! the compi%ercreates one for &ou

    this performs a bit/ise cop&

  • 7/23/2019 CPP_v1.1 OOP

    61/439

    2013-2015 Margit ANTAL

    OOP. C%asses and objects

    //Btack.h#i&nde& MSHR1!#de&ine MSHR1!

    class Btack4pu4lic$ Mtac( int inHapacit ); void push( dou4le inou4le ); dou4le top(); void pop(); 4ool isBull(); 4ool is-mpt();private$ "nt mapac"ty5 dou(le ? m&lements5 dou(le ? mCop57;#endi& /2 MSHR1! 2/

    //Btack.cpp

    #include *Mtac.h*

    Mtac$$Mtac( int inHapacit ){ mHapacit 9 inHapacit; m&lements = new dou(le [ mapac"ty ]5 mSop 9 m-lements;void Mtac$$push( dou4le inou4le ){

    i&( 3isBull()){ 2mSop 9 inou4le; mSop++;

  • 7/23/2019 CPP_v1.1 OOP

    62/439

    2013-2015 Margit ANTAL

    OOP. C%asses and objects

    //CestBtack.cpp#include *Mtac.h*

    int main(){Mtac s5();

    Mtac s6 9 s5; s5.push(5);

    s6.push(6);cout

  • 7/23/2019 CPP_v1.1 OOP

    63/439

    2013-2015 Margit ANTAL

    OOP. C%asses and objects

    Cop& constructor. C $ const C*%

    //Btack.h

    #i&nde& MSHR1!#de&ine MSHR1!

    class Btack4pu4lic$ //Hop constructor Btack$ const Btack* %5private$ int mHapacit; dou4le 2 m-lements; dou4le 2 mSop;7;

    #endi& /2 MSHR1! 2/

    //Btack.cpp

    #include *Mtac.h*

    Mtac::Btack$ const Btack* s %4 mHapacit 9 s.mHapacit; m-lements 9 new dou4le% mHapacit '; int nr 9 s.mSop I s.m-lements; &or( int i9"; i

  • 7/23/2019 CPP_v1.1 OOP

    64/439

    2013-2015 Margit ANTAL

    OOP. C%asses and objects

    //CestBtack.cpp#include *Mtac.h*

    int main(){Mtac s5();

    Mtac s6 9 s5; s5.push(5);

    s6.push(6);cout

  • 7/23/2019 CPP_v1.1 OOP

    65/439

    2013-2015 Margit ANTAL

    OOP. C%asses and objects

    4estructor /hen an object is destro&ed.

    the objects destructor is automatica%%& in2o3ed!

    the memor& used b& the object is freed

    each c%ass has one destructor

    usua%%& p%ace to perform c%eanup /or3 for the object

    if &ou dont dec%are a destructor @ the compi%er /i%% generateone! /hich destro&s the objects member

  • 7/23/2019 CPP_v1.1 OOP

    66/439

    2013-2015 Margit ANTAL

    OOP. C%asses and objects

    4estructor

    S&nta5. C :: DC$%5Mtac$$TMtac(){ i&( m-lements 39 nullptr){ delete%' m-lements;

    m-lements 9 nullptr;

    { // 4loc 4eginMtac s(5"); // s: constructor

    Mtac2 s5 9 new Mtac(F);// s1: constructor s.push();

    s5I>push(5");

    delete s5; //s1: destructors.push(5=); // 4loc end //s: destructor

  • 7/23/2019 CPP_v1.1 OOP

    67/439

    2013-2015 Margit ANTAL

    OOP. C%asses and objects

    4efau%t parameters if the user specifies the arguments @ the defau%ts are ignored

    if the user omits the arguments @ the defau%ts are used

    the defau%t parameters are specified onl&in themethod declaration

    8not in the definition9//Btack.hclass Mtac{pu4lic$ Mtac( "nt "napac"ty 9 F);

    ..;//Btack.cppMtac$$Mtac( "nt "napac"ty){ mHapacit 9 inHapacit; m&lements = new dou(le [ mapac"ty ]5 mSop 9 m-lements;

    //CestBtack.cpp

    Mtac s5(); //capacit$ Btack s25 //capac"ty: EMtac s( 5" ); //capacit$ 5"

  • 7/23/2019 CPP_v1.1 OOP

    68/439

    2013-2015 Margit ANTAL

    OOP. C%asses and objects

    The thispointer e2er& method ca%% passes a pointer to the object for /hich it

    is ca%%ed as hidden parameterha2ing the name this

    ?sage.

    for disambiguation

    Mtac$$Mtac( intmapac"ty ){ th"s F mapac"ty9mapac"ty; //..

  • 7/23/2019 CPP_v1.1 OOP

    69/439

    2013-2015 Margit ANTAL

    OOP. C%asses and objects

    Programming task +Prata,class Gueue{

    enum {U1MNV- 9 5";private$ // pr"ate representat"on to (e deeloped laterpu4lic$

    Uueue(int Ws 9 U1MNV-); // create Wueue with a Ws limitTUueue();4ool isempt() const;4ool is&ull() const;int Wueuecount() const;4ool enWueue(const Ntem Gitem); // add item to end4ool deWueue(Ntem Gitem); // remove item &rom &ront

    ;

  • 7/23/2019 CPP_v1.1 OOP

    70/439

    2013-2015 Margit ANTAL

    OOP. C%asses and objects

    Programming task +Prata,class Gueue{private$

    // class scope de&initions

    // Kode is a nested structure de&inition local to this class

    struct9ode{ Ntem item; struct Kode 2 ne@t;;enum {U1MNV- 9 5";

    // private class mem4ersKode 2 &ront; // pointer to &ront o& UueueKode 2 rear; // pointer to rear o& Uueueint items; // current num4er o& items in Uueueconst int Wsi8e; // ma@imum num4er o& items in Uueue

    ;

  • 7/23/2019 CPP_v1.1 OOP

    71/439

    2013-2015 Margit ANTAL

    Modu%e "

    Object-Oriented Programming

    d2anced C%ass Features

  • 7/23/2019 CPP_v1.1 OOP

    72/439

    2013-2015 Margit ANTAL

    OOP. d2anced c%ass features

    Content In%ine functions

    Stac3 2s 1eap

    rra& of objects 2s arra& of pointers

    Passing function arguments

    Static members

    Friend functions! friend c%asses

    ested c%asses

    OOP d d % f

  • 7/23/2019 CPP_v1.1 OOP

    73/439

    2013-2015 Margit ANTAL

    OOP. d2anced c%ass features

    Nnlinefunctions

    designed to speed up programs 8%i3e macros9

    the compi%er rep%aces the function ca%% /ith the

    function code 8no function ca%%K9 ad2antage. speed

    disad2antage. code bloat

    e5 0; function ca%%s @ 0; functions siEe

    OOP d d % f t

  • 7/23/2019 CPP_v1.1 OOP

    74/439

    2013-2015 Margit ANTAL

    OOP. d2anced c%ass features

    1o/ to ma3e a function inline

    use theinline3e&/ord either in function dec%arationor in function definition

    both member and standa%one functions can be inline

    common practice.

    p%ace the imp%ementation of theinlinefunctioninto the header fi%e

    on%& sma%% functions are e%igib%e as inline the compi%er ma& comp%ete%& ignore &our reHuest

    OOP d d % f t

  • 7/23/2019 CPP_v1.1 OOP

    75/439

    2013-2015 Margit ANTAL

    OOP. d2anced c%ass features

    inlinefunction e5amp%es

    "nl"nedou4le sWuare(dou4le a){return a 2 a;

    classCalue{ int value;pu4lic$ "nl"neint getCalue(){ return value;

    "nl"nevoid setCalue( int value ){thisI>value 9 value;

    ;

    OOP d d % f t

  • 7/23/2019 CPP_v1.1 OOP

    76/439

    2013-2015 Margit ANTAL

    OOP. d2anced c%ass features

    Stac3 2s 1eap 1eap < 4&namic a%%ocation

    Stac3 < utomatic a%%ocation

    o"d draw$%4o"nt ? p = new o"nt$%5p-,moe$HAH%5//...

    7

    o"d draw$%4o"nt p$%5p.moe$IAI%5//...

    7

    OOP. d2anced c%ass features

  • 7/23/2019 CPP_v1.1 OOP

    77/439

    2013-2015 Margit ANTAL

    OOP. d2anced c%ass features

    rra& of objects class o"nt{

    int @, ; pu4lic$

    Xoint( int @9", int 9"); //...

    ;

    .Point .Point .Point .Point

    5. ;&. ;

    5. ;&. ;

    5. ;&. ;

    5. ;&. ;

    Point t0 > ne/ PointN Q

    t0

    Point t0N Q

    $hat is the difference bet/een these t/o arra&s

    OOP. d2anced c%ass features

  • 7/23/2019 CPP_v1.1 OOP

    78/439

    2013-2015 Margit ANTAL

    OOP. d2anced c%ass features

    rra& of pointers Xoint 22 t6 9 new Xoint2% ';&or(int i9"; i

  • 7/23/2019 CPP_v1.1 OOP

    79/439

    2013-2015 Margit ANTAL

    OOP. d2anced c%ass features

    Static members. staticmethods

    staticdata

    Functions be%onging to a class scope/hich dont accessobjects data can be static

    Static methods cant be constmethods 8the& do not accessobjects state9

    The& are not ca%%ed on specific objectsthe& ha2e nothis

    pointer

    OOP. d2anced c%ass features

  • 7/23/2019 CPP_v1.1 OOP

    80/439

    2013-2015 Margit ANTAL

    OOP. d2anced c%ass features

    Static members

    //omplex.hclass omplex{pu4lic$ Homple@(int re9", int im9");

    stat"cint getKumHomple@();// ...private$ stat"cint numcomplex; dou4le re, im;;

    //omplex.cpp

    "ntomplex::numcomplex = 05

    int omplex::getKumHomple@(){return num1comple@;

    omplex$$Homple@(int re, int im){ thisI>re 9 re;

    thisI>im 9 im;++numcomplex;

    initia%iEing static c%ass member

    instance counter

    OOP. d2anced c%ass features

  • 7/23/2019 CPP_v1.1 OOP

    81/439

    2013-2015 Margit ANTAL

    OOP. d2anced c%ass features

    Static method in2ocation

    Homple@ 85(5,6), 86(6,), 8;cout

  • 7/23/2019 CPP_v1.1 OOP

    82/439

    2013-2015 Margit ANTAL

    OOP. d2anced c%ass features

    Comp%e5 E080!:9! E:8:!"9! E"Q

    re. 0im. :

    re. :im. "

    re. ;im. ;

    numcomp%e5. "

    )ach object hasits o/n reand im

    On%& one cop& of

    the static member

    OOP. d2anced c%ass features

  • 7/23/2019 CPP_v1.1 OOP

    83/439

    2013-2015 Margit ANTAL

    OOP. d2anced c%ass features

    C%asses 2s Structs defau%t access specifier

    c%ass. private

    struct. pu4lic

    c%ass. data + methods! can be used po%imorphica%%& struct. most%& data + con2enience methods

    OOP. d2anced c%ass features

  • 7/23/2019 CPP_v1.1 OOP

    84/439

    2013-2015 Margit ANTAL

    OOP. d2anced c%ass features

    C%asses 2s structures

    class l"st4

    pr"ate:

    struct node

    4

    node ?next5

    "nt al5

    node$ "nt al=0A node ? next=9J;;%:al$al%A next$next%47

    75

    node ? head5

    pu(l"c:

    l"st $%5

    Dl"st $%5 o"d "nsert $"nt a%5

    75

    OOP. d2anced c%ass features

  • 7/23/2019 CPP_v1.1 OOP

    85/439

    2013-2015 Margit ANTAL

    OOP. d2anced c%ass features

    Passing function arguments b& 2a%ue

    the function /or3s on a cop& of the 2ariab%e

    b& reference

    the function /or3s on the origina% 2ariab%e! ma& modif& it b& constant reference

    the function /or3s on the origina% 2ariab%e! ma& not modif&82erified b& the compi%er9

    OOP. d2anced c%ass features

  • 7/23/2019 CPP_v1.1 OOP

    86/439

    2013-2015 Margit ANTAL

    OOP. d2anced c%ass features

    Passing function arguments

    o"d #1$"nt x% 4x = x + 157o"d #2$"nt* x% 4x = x + 157o"d #H$const "nt* x% 4x = x + 157o"d #K$"nt ?x% 4?x = ?x + 157

    "nt ma"n$%4"nt y = E5#1$y%5#2$y%5#H$y%5#K$*y%5return 05

    7

    passing primiti2e 2a%ues

    OOP. d2anced c%ass features

  • 7/23/2019 CPP_v1.1 OOP

    87/439

    2013-2015 Margit ANTAL

    OOP. d2anced c%ass features

    Passing function arguments

    o"d #1$o"nt p%5o"d #2$o"nt* p%5o"d #H$const o"nt* p%5o"d #K$o"nt ?p%5

    "nt ma"n$%4o"nt p1$HAH%5#1$p1%5#2$p1%5#H$p1%5#K$*p1%5return 05

    7

    passing objects

    cop& constructor -ill )e use' on t!e argument

    onl& constmet!o's o( t!e class can )einvoke' on t!is argument

    OOP. d2anced c%ass features

  • 7/23/2019 CPP_v1.1 OOP

    88/439

    2013-2015 Margit ANTAL

    OOP. d2anced c%ass features

    &riend functions! &riendc%asses! &riend memberfunctions

    friends are a%%o/ed to access pri2ate members of a c%ass

    ?se it rare%&

    operator o2er%oading

    OOP. d2anced c%ass features

  • 7/23/2019 CPP_v1.1 OOP

    89/439

    2013-2015 Margit ANTAL

    &riend2s staticfunctions

    class Cest{private$ int iCalue; static int sCalue;pu4lic$

    Sest( int in )$iCalue( in ){ o"d pr"nt$% const5 stat"c o"d pr"nt$ const Cest* what %5 #r"end o"d pr"nt$ const Cest* what %5;

    OOP. d2anced c%ass features

  • 7/23/2019 CPP_v1.1 OOP

    90/439

    2013-2015 Margit ANTAL

    &riend2s staticfunctions

    int Sest $$ sCalue 9 ";

    o"d Cest::pr"nt$% const4 cout>em(er: >"@alueendl57

    o"d Cest::pr"nt$ const Cest* what %4 cout>Btat"c: >what."@alueendl5

    7

    o"d pr"nt$ const Cest* what %4 cout>8r"end: >what."@alueendl57

    int main() { Sest test( 5" ); test.pr"nt$%5 Cest::pr"nt$ test %5 pr"nt$ test %5

    OOP. d2anced c%ass features

  • 7/23/2019 CPP_v1.1 OOP

    91/439

    2013-2015 Margit ANTAL

    &riendc%ass 2s &riendmember function

    class ;"st{private$

    Eist-lement 2 head;pu4lic$

    4ool &ind( int e );

    ;

    class ;"st&lement{private$

    int e;Eist-lement 2 ne@t;#r"end class ;"st5...

    ;

    class ;"st&lement{private$

    int e;Eist-lement 2 ne@t;#r"end class ;"st::#"nd$ "nt key%5...

    ;

    OOP. d2anced c%ass features

  • 7/23/2019 CPP_v1.1 OOP

    92/439

    2013-2015 Margit ANTAL

    Returning a reference to a constobject// ers"on 1ector"nt,ax(const vector G v5, const vector G v6){ i& (v5.si8e() > v6.si8e()) return v5; else return v6;

    // ers"on 2const ector"nt, *ax(const vector G v5, const vector G v6){ i& (v5.si8e() > v6.si8e())

    return v5;else

    return v6;

    Cop&constructorin2ocation

    Moreefficient

    The reference shou%d be toa non-%oca% object

    OOP. d2anced c%ass features

  • 7/23/2019 CPP_v1.1 OOP

    93/439

    2013-2015 Margit ANTAL

    ested c%asses the c%ass dec%ared /ithin another c%ass is ca%%ed a

    nested class

    usua%%& he%per c%asses are dec%ared as nested

    // @ers"on 1class Gueue{private$ // class scope de&initions

    // Kode is a nested structure de&inition local to this classstruct9ode{Ntem item; struct Kode 2 ne@t;;

    ...;

    OOP. d2anced c%ass features

  • 7/23/2019 CPP_v1.1 OOP

    94/439

    2013-2015 Margit ANTAL

    ested c%asses NPrata

    // @ers"on 2

    class Gueue{

    // class scope de&initions// Kode is a nested class de&inition local to this class

    class9ode{pu4lic$

    Ntem item;Kode 2 ne@t;9ode$const tem * "% : "tem$"%A next$0% 4 7

    ;//...

    ;

    o'e visi)ilit&///

    OOP. d2anced c%ass features

  • 7/23/2019 CPP_v1.1 OOP

    95/439

    2013-2015 Margit ANTAL

    ested c%asses a nested c%ass dec%ared in a privatesection of a c%ass .

    is %oca% to c%ass 8on%& c%ass can use it9

    a nested c%ass dec%ared in a protecte'section of a c%ass . can be used both in and in the deri2ed c%asses of

    a nested c%ass dec%ared in a pu)lic section of a c%ass .

    is a2ai%ab%e to the outside /or%d 8 $$ P 4;9

    OOP. d2anced c%ass features

  • 7/23/2019 CPP_v1.1 OOP

    96/439

    2013-2015 Margit ANTAL

    Features of a #ell-behavedC++ c%ass imp%icit constructor

    C :: C$%4 L 7 destructor

    C :: DC$%4 L 7 cop& constructor

    C :: C$ const C* %4 L 7 assignment operator 8see next module9

    C :: operator=$ const C* %4 L 7

  • 7/23/2019 CPP_v1.1 OOP

    97/439

    2013-2015 Margit ANTAL

    Modu%e

    Object-Oriented Programming

    Operator o2er%oading

    OOP. Operator o2er%oading

  • 7/23/2019 CPP_v1.1 OOP

    98/439

    2013-2015 Margit ANTAL

    Content Objecti2es

    T&pes of operators

    rithmetic operators

    IncrementAdecrement InserterAe5tractor operators

    assignment operator

    inde5 operator

    re%ationa% and eHua%it& operators con2ersion operators

    OOP. Operator o2er%oading

  • 7/23/2019 CPP_v1.1 OOP

    99/439

    2013-2015 Margit ANTAL

    Objecti2e To ma3e the c%ass usage easier! more intuiti2e

    the abi%it& to read an object using the e@tractoroperator 8>>9

    -mploee e5; cin >> e;

    the abi%it& to /rite an object using the inserter operator 8

  • 7/23/2019 CPP_v1.1 OOP

    100/439

    2013-2015 Margit ANTAL

    Limitations ou cannot add ne/ operator s&mbo%s On%& the e5isting operators

    meaning can be redefined

    Some operators cannot be o2er%oaded.

    .8member access in an object9

    $$8scope reso%ution operator9

    si8eo&

    O$

    ou cannot change the arit&8the number of arguments9 of the operator

    ou cannot change the prece'enceor associativit&of the operator

    OOP. Operator o2er%oading

  • 7/23/2019 CPP_v1.1 OOP

    101/439

    2013-2015 Margit ANTAL

    1o/ to imp%ement /rite a function /ith the name operatorsym(ol,

    a%ternati2es.

    method of &our c%ass

    g%oba% function 8usua%%& a friend of the c%ass9

    OOP. Operator o2er%oading

  • 7/23/2019 CPP_v1.1 OOP

    102/439

    2013-2015 Margit ANTAL

    There are " t&pes of operators. operators that must be methods 8mem)er (unctions9

    the& dont ma3e sense outside of a c%ass.

    assignment operator. operator9

    operators that must be glo)al (unctions

    the %eft-hand side of the operator is a 2ariab%e of different t&pe than &our c%ass.operator

    cout

  • 7/23/2019 CPP_v1.1 OOP

    103/439

    2013-2015 Margit ANTAL

    Choosing argument t&pes. 2a%ue 2s reference

    Prefer passing-b&-reference instead of passing-b&-2a%ue

    const 2s non const

    Prefer const un%ess &ou modif& it

    Choosing return t&pes &ou can specif& an& return t&pe! ho/e2er

    fo%%o/ the bui%t-in t&pes ru%e.

    comparison a%/a&s return 4ool arithmetic operators return an object representing the resu%t of the arithmetic

    OOP. Operator o2er%oading

  • 7/23/2019 CPP_v1.1 OOP

    104/439

    2013-2015 Margit ANTAL

    The Comp%e5 c%ass. [email protected], [email protected]

    class "#P$%

    1omple2

    - re. doub%e

    - im. doub%e

    + Comp%e58doub%e! doub% e9+ Comp%e58Comp%e5'9

    + setRe8doub %e9 . 2oid

    + setIm8dou b%e 9 . 2oid

    + getRe89 . dou b%e Huer&J

    + getIm89 . doub% e Huer&J

    + print89 . 2oid Hue r&J

    Binc%ude Comp%e5hBinc%ude ViostreamWusing namespace stdQ

    Comp%e5..Comp%e58 doub%e re! doub%e im9.re8 re9! im8im9 J

    Comp%e5..Comp%e58const Comp%e5' orig9.re8 origre9! im8origim9J

    2oid Comp%e5..setRe8 doub%e re9this-Wre > reQJ

    2oid Comp%e5..setIm8 doub%e im9 this-Wim > imQJdoub%e Comp%e5..getRe89 const return this-WreQJdoub%e Comp%e5..getIm89 const return this-WimQJ

    2oid Comp%e5..print89 const coutVVreVV+VVimVViQJ

    OOP. Operator o2er%oading

  • 7/23/2019 CPP_v1.1 OOP

    105/439

    2013-2015 Margit ANTAL

    rithmetic operators 8member func9 unar& minus

    binar& minus

    Homple@ Homple@$$operator-$% const{

    Homple@ temp(IthisI>re, IthisI>im); return temp;

    Homple@ Homple@$$operator-$ const omplex* )% const{ Homple@ temp(thisI>re I 8.re, thisI>imI 8.im); return temp;

    OOP. Operator o2er%oading

  • 7/23/2019 CPP_v1.1 OOP

    106/439

    2013-2015 Margit ANTAL

    IncrementA4ecrement operators postincrement.int i 9 5"; int A 9 i++; // A Y 5"

    preincrement. int i 9 5"; int A 9 ++i; // A Y 55 The C++ standard specifies that the prefi5 increment and decrement

    return an lvalue 8%eft 2a%ue9

    OOP. Operator o2er%oading

  • 7/23/2019 CPP_v1.1 OOP

    107/439

    2013-2015 Margit ANTAL

    IncrementA4ecrement operators 8member func9Homple@G Homple@$$operator++(){ //pre#"x (thisI>re)++; (thisI>im)++; return 2this;

    Homple@ Homple@$$operator++( int ){ //post#"x Homple@ temp(2this); (thisI>re)++; (thisI>im)++; return temp;

    W!ic! one is more e((icientW!&

    OOP. Operator o2er%oading

  • 7/23/2019 CPP_v1.1 OOP

    108/439

    2013-2015 Margit ANTAL

    InserterA)5tractor operators 8standa%one func9//complex.hclass Homple@ {pu4lic$ #r"end ostream*operator( "stream*is, Homple@G c); //...;

    //complex.cppostream*operator

  • 7/23/2019 CPP_v1.1 OOP

    109/439

    2013-2015 Margit ANTAL

    InserterA)5tractor operators %&nta:

    ostream*operator$ ostream*osA const C* out%

    "stream*operator,,$ "stream*"sA C* "n%

    Remar3s. Streams are a%/a&spassed by reference

    :$h& shou%d inserter operator return an ostream5

    :$h& shou%d e5tractor operator return anistream5

    OOP. Operator o2er%oading

  • 7/23/2019 CPP_v1.1 OOP

    110/439

    2013-2015 Margit ANTAL

    InserterA)5tractor operators ?sage.

    Homple@ 85, 86;cout85>>86;

    //nsertercout

  • 7/23/2019 CPP_v1.1 OOP

    111/439

    2013-2015 Margit ANTAL

    ssignment operator :$hen shou%d be o2er%oaded

    :$hen bit/ise cop& is not satisfactor& 8eg if &ou ha2e

    d&namica%%& a%%ocated memor&

    /hen /e shou%d imp%ement the cop& constructor and thedestructor too9

    )5 our Stac3 c%ass

    %&nta:ZG operator9( const ZG rhs);

    OOP. Operator o2er%oading

  • 7/23/2019 CPP_v1.1 OOP

    112/439

    2013-2015 Margit ANTAL

    ssignment operator 8member func9 %&nta:ZG operator9( const ZG rhs);

    :Is the return t&pe necessar&

    na%&Ee the fo%%o/ing e5amp%e code

    omplex )1$1A2%A )2$2AH%A )H$1A1%5)H = )15)2 = )1 = )H5

    OOP. Operator o2er%oading

  • 7/23/2019 CPP_v1.1 OOP

    113/439

    2013-2015 Margit ANTAL

    ssignment operator e5amp%eMtacG Mtac$$operator9(const MtacG rhs) { i& (th"s = *rhs) { //delete lhs delete %' thisI>m-lements; //copy rhs mHapacit 9 rhs.mHapacit;

    m-lements 9 new dou4le% mHapacit '; int nr 9 rhs.mSop I rhs.m-lements; &or (int i 9 "; i < nr; ++i) { m-lements% i ' 9 rhs.m-lements% i '; mSop 9 m-lements + nr; return 2this;

    OOP. Operator o2er%oading

  • 7/23/2019 CPP_v1.1 OOP

    114/439

    2013-2015 Margit ANTAL

    ssignment operator2s Copy constructoromplex )1$1A2%A )2$HAK%5 //onstructor

    omplex )H = )15 //opy constructor

    omplex )K$)2%5 //opy constructor

    )1 = )25 //Mss"gnment operator

    OOP. Operator o2er%oading

    Subscript operator. needed for arra&s 8member func9

  • 7/23/2019 CPP_v1.1 OOP

    115/439

    2013-2015 Margit ANTAL

    Subscript operator. needed for arra&s 8member func9

    Suppose &ou /ant &our o/n d&namica%%& a%%ocated C-st&%e

    arra&imp%ement &our o/n Hrra#i&nde& H001!#de&ine H001!class Mrray{pu(l"c: Hrra( int si8e 9 5" ); THrra(); dou4leG operator[]( int inde@ ); dou4leG operator[]( int inde@ ) const;protected: dou4le 2 m-lems; int mMi8e;pr"ate: Hrra( const HrraG); HrraG operator9( const HrraG);;#endi& /2 001! 2/

    Pro2ides read-on%& access

    OOP. Operator o2er%oading

    Imp%ementation

  • 7/23/2019 CPP_v1.1 OOP

    116/439

    2013-2015 Margit ANTAL

    Imp%ementationHrra$$Mrray( int si8e ){ i&( si8e < " ){ si8e 9 5"; thisI>mMi8e 9 si8e; thisI>m-lems 9 new dou4le% mMi8e ';

    Hrra$$DMrray$%{ i&( thisI>m-lems 39 KDEE ){ delete%' m-lems;

    dou4leG Hrra$$operator[]( int inde@ ){ i&( inde@

  • 7/23/2019 CPP_v1.1 OOP

    117/439

    2013-2015 Margit ANTAL

    %' p

    void printrra(const Mrray*arr, si8e1t si8e) { &or (si8e1t i 9 "; i < si8e; i++) { cout

  • 7/23/2019 CPP_v1.1 OOP

    118/439

    2013-2015 Margit ANTAL

    g & y

    ( Re, Calue )

    )5. Xe& @ string! Da%ue @ doub%e

    6ome-ork

    OOP. Operator o2er%oading

    Re%ationa% and eHua%it& operators

  • 7/23/2019 CPP_v1.1 OOP

    119/439

    2013-2015 Margit ANTAL

    H & p

    used for search and sort

    the container must be ab%e to compare the stored objects

    4ool operator ==( const XointG p5, const XointG p6){ return p5.getZ() 99 p6.getZ() GG p5.get() 99 p6.get();

    4ool operator ( const XointG p5, const XointG p6){ return p5.distance(Xoint(",")) < p6.distance(Xoint(","));

    seto"nt, p5 ectoro"nt, 5 //...sort$.(eg"n$%A .end$%%5

    OOP. Operator o2er%oading

    The function ca%% operator ()

  • 7/23/2019 CPP_v1.1 OOP

    120/439

    2013-2015 Margit ANTAL

    Instances of c%asses o2er%oading this operator beha2e asfunctions too 8the& are function objects > function + object9

    #i&nde& CED-1!#de&ine CED-1!classMdd@alue{

    int value;pu4lic$ ddCalue( int inCalue 9 5); void operator$%( intG what );;#endi& /2 CED-1! 2/

    #include *ddCalue.h*

    ddCalue$$ddCalue( int inCalue ){

    thisI>value 9 inCalue;void ddCalue$$operator$%( intG what ){ what +9 thisI>value;

    OOP. Operator o2er%oading

    The function ca%% operator

  • 7/23/2019 CPP_v1.1 OOP

    121/439

    2013-2015 Margit ANTAL

    Mdd@alue#unc(6);int arra%'9{5, 6, ;&or( int @ $ arra ){ #unc(@);

    &or( int @$ arra ){ cout

  • 7/23/2019 CPP_v1.1 OOP

    122/439

    2013-2015 Margit ANTAL

    used freHuent%& for defining sorting criterion

    struct &mployeeompare{ 4ool operator$%( const -mploeeG e5, const -mploeeG e6){ i&( e5.getEastKame() 99 e6.getEastKame())

    return e5.getBirstKame() < e6.getBirstKame(); else return e5.getEastKame() < e6.getEastKame();

    ;

    OOP. Operator o2er%oading

    Function ca%% operator

  • 7/23/2019 CPP_v1.1 OOP

    123/439

    2013-2015 Margit ANTAL

    sorted container

    set&mployeeA &mployeeompare,s;-mploee e5; e5.setBirstKame(*Par4ara*);e5.setEastKame(*Eisov*);

    -mploee e6; e6.setBirstKame(*Lohn*);e6.setEastKame(*Mtein4ec*);-mploee e; e.setBirstKame(*ndrew*);e.setEastKame(*Bole*);

    s.insert( e5 ); s.insert( e6 ); s.insert( e );

    &or( -mploee emp $ s){ emp.displa();

    OOP. Operator o2er%oading

    Sorting e%ements of a gi2en type.

  • 7/23/2019 CPP_v1.1 OOP

    124/439

    2013-2015 Margit ANTAL

    .o2erride operators. 7! 88

    .define a function objectcontaining the comparison

    W!ic! one to use

    :1o/ man& sorted criteria can be defined using method

    :1o/ man& sorted criteria can be defined using method

    OOP. Operator o2er%oading

    $riting con2ersion operators

  • 7/23/2019 CPP_v1.1 OOP

    125/439

    2013-2015 Margit ANTAL

    class omplex{pu4lic$ operator str"ng() const; //;

    Homple@$$operator str"ng$%const{ stringstream ss; ss

  • 7/23/2019 CPP_v1.1 OOP

    126/439

    2013-2015 Margit ANTAL

    O2er%oading operator

    O2er%oading operator @

    OOP: 9evie-

    Find a%% possib%e errors or shortcommingsK

  • 7/23/2019 CPP_v1.1 OOP

    127/439

    2013-2015 Margit ANTAL

    (5) classMrray{(6) pu4lic$() rra (int n) $ rep1(new int %n') { () rra (rraG rhs) $ rep1(rhs.rep1) { (F) Trra () { delete rep1; (=) rraG operator 9 (rra rhs) { rep19 rhs.rep1;

    (?) intG operator %' (int n) { return Grep1%n'; () private$(\) int 2 rep1;(5") ; // rra

    Source. http.AA///cshe%sin3ifiAuA2iha2ainA30"AgeaAe5erAe5er:htm%

    %olution reuire'/

    It is gi2en the fo%%o/ing programK

  • 7/23/2019 CPP_v1.1 OOP

    128/439

    2013-2015 Margit ANTAL

    #include

    int main(){std$$cout

  • 7/23/2019 CPP_v1.1 OOP

    129/439

    2013-2015 Margit ANTAL

    class ;ogger4pu(l"c:

    stat"c ;ogger? nstance$%54ool openEogBile(std$$string logBile);void writeSoEogBile();4ool closeEogBile();

    pr"ate:;ogger$%475 // r"ate so that "t can not (e called

    ;ogger$;ogger const*%475 // copy constructor "s pr"ate;ogger* operator=$;ogger const*%475// ass"gnment operator "s pr"atestat"c ;ogger? mpnstance5

    75

    http.AA///&o%inu5comAT?TORILSAC++Sing%etonhtm%

    %ingleton Design Pattern

    static

    http://www.yolinux.com/TUTORIALS/C++Singleton.htmlhttp://www.yolinux.com/TUTORIALS/C++Singleton.html
  • 7/23/2019 CPP_v1.1 OOP

    130/439

    2013-2015 Margit ANTAL

    class ;rame-or...

    %ingleton

    - uniHueInstance

    - sing%eton4ata

    + Instance89

    return uniHue Instance+ Sing%etonOperation89

    + GetSing%eton4ata89

    static

    static )nsure that onl& one instanceof a c%ass is created

    Pro2ide a glo)al point o( accessto the object

  • 7/23/2019 CPP_v1.1 OOP

    131/439

    2013-2015 Margit ANTAL

    Modu%e *

    Object-Oriented Programming

    Pub%ic Inheritance

    OOP. Inheritance

    Inheritance

    i % ti hi b%i i h it

  • 7/23/2019 CPP_v1.1 OOP

    132/439

    2013-2015 Margit ANTAL

    is-are%ationship - pub%ic inheritance

    protected access

    2irtua% member function

    ear%& 8static9 binding 2s %ate 8d&namic9 binding

    abstract base c%asses

    pure 2irtua% functions

    2irtua% destructor

    OOP. Inheritance

    pu4licinheritance

    i % ti hi

    class cppin!eritance

    $mplo&ee

    - firstame . strin g

    - %astame. string

    - sa%a r&. dou b%e

    + )mp%o &ee8string! string! doub% e9

    + getFirstame 89 . string Huer&J

  • 7/23/2019 CPP_v1.1 OOP

    133/439

    2013-2015 Margit ANTAL

    is-are%ationship

    base c%ass.)mp%o&ee

    deri2ed c%ass.Manager

    ou can do /ith inheritance

    add data

    e5 department

    add functionality

    e5getepartment(), setepartment()

    modify methods) behavior e5print()

    + setFirstam e8strin g9 . 2oi d

    + getLa stame 89 . string Huer&J

    + setLastame8string9 . 2oid

    + getSa%ar&89 . doub% e Huer&J

    + setSa% ar&8doub% e9 . 2oid

    + pri nt (ostre am* " voi d +,u ery -

  • 7/23/2019 CPP_v1.1 OOP

    134/439

    2013-2015 Margit ANTAL

    base c%asss pri2atemembers can not be accessed in aderi2ed c%ass

    base c%asss protectedmembers can be accessed in aderi2ed c%ass

    base c%asss pub%icmembers can be accessed froman&/here

    OOP. Inheritance

    pu4licinheritance

    class &mployee{

  • 7/23/2019 CPP_v1.1 OOP

    135/439

    2013-2015 Margit ANTAL

    class &mployee{pu4lic$

    -mploee(string &irstKame 9 **, string lastKame 9 **,dou4le salar 9 ".") $ &irstKame(&irstKame),

    lastKame(lastKame),salar(salar) {

    //...

    ;

    classanager:pu(l"c&mployee{ string department;pu4lic$ anager(); anager( string &irstKame, string lastKame, dou4le salar,

    string department ); //...;

    OOP. Inheritance

    4eri2ed c%asss constructors

    (){

  • 7/23/2019 CPP_v1.1 OOP

    136/439

    2013-2015 Margit ANTAL

    anager$$anager(){

    )mp%o&ees constructor in2ocation @ 4efau%t constructor can be in2o3ed imp%icit%&

    OOP. Inheritance

    4eri2ed c%asss constructors

    g (){

  • 7/23/2019 CPP_v1.1 OOP

    137/439

    2013-2015 Margit ANTAL

    anager$$anager(){

    anager$$anager(string &irstKame, string lastKame, dou4le salar,string department)$ &mployee$#"rst9ameA last9ameA salary%,

    department(department){

    )mp%o&ees constructor in2ocation @ 4efau%t constructor can be in2o3ed imp%icit%&

    base c%asss constructor in2ocation < constructor initiali!er list

    arguments for the base c%asss constructor are specified in the definition of a deri2ed c%asss constructor

    OOP. Inheritance

    1o/ are deri2ed c%asss objects constructed

    bottom up order.

  • 7/23/2019 CPP_v1.1 OOP

    138/439

    2013-2015 Margit ANTAL

    bottom uporder.

    base c%ass constructor in2ocation

    member initia%iEation

    deri2ed c%asss constructor b%oc3 destruction

    in the opposite order

    )mp%o&ee

    Manager

    OOP. Inheritance

    Method o2erriding

    class -mploee {

    class -mploee {

    class &mployee{

  • 7/23/2019 CPP_v1.1 OOP

    139/439

    2013-2015 Margit ANTAL

    class -mploee {pu4lic$

    "rtualvoidpr"nt( ostreamG) const;;

    classanager$pu4lic -mploee{pu4lic$

    "rtualvoidpr"nt(ostreamG) const;;

    class -mploee {pu4lic$

    "rtualvoidpr"nt( ostreamG) const;;

    class &mployee{pu4lic$

    "rtualvoidpr"nt( ostreamG) const;;

    OOP. Inheritance

    Method o2erriding

    class -mploee {

    class &mployee {

  • 7/23/2019 CPP_v1.1 OOP

    140/439

    2013-2015 Margit ANTAL

    class -mploee {pu4lic$

    "rtualvoidpr"nt( ostreamG) const;;

    void anager$$pr"nt(ostreamG os) const{ &mployee::pr"nt$os%5

    os

  • 7/23/2019 CPP_v1.1 OOP

    141/439

    2013-2015 Margit ANTAL

    non 2irtua% functions are bound statica%%&

    compi%e time 2irtua%functions are bound d&namica%%&

    run time

    OOP. Inheritance

    Po%&morphism

    "d " tMll$ t t & l ?,* %4

  • 7/23/2019 CPP_v1.1 OOP

    142/439

    2013-2015 Margit ANTAL

    o"d pr"ntMll$ const ector&mployee?,* emps%4 #or$ "nt "=05 "emps.s")e$%5 ++"%4 emps["]-,pr"nt$cout%5 coutendl5 77

    "nt ma"n$"nt argcA char?? arg% 4 ector&mployee?, 5 &mployee e$>Oohn>A >Bm"th>A 1000%5 .push(ack$*e%5 anager m$>Barah>A >arker>A 2000A >Bales>%5 .push(ack$*m%5 coutendl5 pr"ntMll$ %5 return 05

    7

    Output:Lohn Mmith 5"""Marah Xarer 6""" Males

    OOP. Inheritance

    Po%&morphism

    a t&pe /ith 2irtua% functions is ca%%ed a po%&morphic t&pe

  • 7/23/2019 CPP_v1.1 OOP

    143/439

    2013-2015 Margit ANTAL

    &p p & p &p

    po%&morphic beha2ior precon'itions.

    the member function must be 2irtua%

    objects must be manipu%ated through pointersor references

    &mployee :: pr"nt$ os %static binding < no

    po%&morphism

    OOP. Inheritance

    Po%&morphism < Dirtua% Function Tab%e

    class &mployee4(l" )mp%o&ee..print

    firstame.UU

    firstame.UU

  • 7/23/2019 CPP_v1.1 OOP

    144/439

    2013-2015 Margit ANTAL

    pu(l"c:"rtualo"d pr"nt$ostream*% const5

    //...75

    class anager:pu(l"c &mployee4"rtual o"d pr"nt$ostream*% const5

    //...75

    &mployee e1A e25anager m1A m25

    firstame.UU%astame.UUsa%ar&.;;

    firstame.UU%astame.UUsa%ar&.;;

    e1

    e2

    )mp%o&ee..print

    Manager..print

    %astame.UUsa%ar&.;;department2tb%

    firstame.%astame.UUsa%ar&.;;'epartment

    firstame.UU%astame.UUsa%ar&.;;'epartment

    m1

    m2

    vt)l

    vt)l

    vt)l

    vt)l

    Discussion///-mploee 2 pe;pe 9 Ge5; peI>print();//PPP

    pe 9 Gm6; peI>print();//PPP

    OOP. Inheritance

    bstract c%asses

    used for representing abstract concepts

  • 7/23/2019 CPP_v1.1 OOP

    145/439

    2013-2015 Margit ANTAL

    used as base c%ass for other c%asses

    no instances can be created

    OOP. Inheritance

    bstract c%asses < pure 2irtua% functions

    l Bh 4 // ( t t l

  • 7/23/2019 CPP_v1.1 OOP

    146/439

    2013-2015 Margit ANTAL

    class Bhape4 // a(stract class

    pu(l"c:

    "rtualo"d rotate$"nt% = 05 // pure "rtual #unct"on

    "rtualo"d draw$% = 05 // pure "rtual #unct"on

    // ...

    75

    Bhape s5 //PPP

    OOP. Inheritance

    bstract c%asses < pure 2irtua% functions

    class Bhape4 // a(stract class

  • 7/23/2019 CPP_v1.1 OOP

    147/439

    2013-2015 Margit ANTAL

    class Bhape4 // a(stract class

    pu(l"c:

    "rtualo"d rotate$"nt% = 05 // pure "rtual #unct"on

    "rtualo"d draw$% = 05 // pure "rtual #unct"on

    // ...

    75

    Bhape s5 //omp"ler error

    OOP. Inheritance

    bstract c%ass @ concrete c%ass

    class o"nt4 /? ?/ 75

  • 7/23/2019 CPP_v1.1 OOP

    148/439

    2013-2015 Margit ANTAL

    class o"nt4 /? ... ?/ 75

    class "rcle :pu(l"c Bhape4

    pu(l"c:

    o"d rotate$"nt%5 // oerr"de Bhape::rotate

    o"d draw$%5 // oerr"de Bhape::draw

    "rcle$o"nt pA "nt r% 5

    pr"ate:o"nt center5

    "nt rad"us5

    75

    OOP. Inheritance

    bstract c%ass @ abstract c%ass

    class olygon : pu(l"c Bhape4

  • 7/23/2019 CPP_v1.1 OOP

    149/439

    2013-2015 Margit ANTAL

    class olygon :pu(l"c Bhape4

    pu(l"c:

    // draw$% and rotate$% are not oerr"dden

    75

    olygon p5 //omp"ler error

    OOP. Inheritance

    Dirtua% destructor

    )2er& c%ass ha2ing at %east one 2irtua% function shou%dh i t % d t t $h

  • 7/23/2019 CPP_v1.1 OOP

    150/439

    2013-2015 Margit ANTAL

    ha2e 2irtua% destructor $h&

    class Z{pu4lic$

    // ...

    TZ();;

    OOP. Inheritance

    Dirtua% destructor

    void deleteMll( -mploee 22 emps, int si8e){&or( int i9"; i

  • 7/23/2019 CPP_v1.1 OOP

    151/439

    2013-2015 Margit ANTAL

    &or( int i9"; i

  • 7/23/2019 CPP_v1.1 OOP

    152/439

    2013-2015 Margit ANTAL

    Modu%e ,

    Object-Oriented Programming

    Object re%ationships

    OOP. Object re%ationships

    Content

    The is-are%ationship

  • 7/23/2019 CPP_v1.1 OOP

    153/439

    2013-2015 Margit ANTAL

    The has-are%ationship

    Pri2ate inheritance

    Mu%tip%e inheritance

    OOP. Object re%ationships

    The is-are%ationship < Client)s vie# (

    /or3s in on%& one direction"

    % ) bj i % %

    Super

  • 7/23/2019 CPP_v1.1 OOP

    154/439

    2013-2015 Margit ANTAL

    e2er& %u)objectisa%so a%uperone

    but %uperobject is nota%u)Sub

    void #oo1( const MuperG s);

    void #oo2( const Mu4G s);Muper super;Mu4 su4;

    #oo1(super); //!#oo1(su4); //!#oo2(super); //9C !#oo2(su4); //!

    OOP. Object re%ationships

    The is-are%ationship < Client)s vie# (/

    Super

  • 7/23/2019 CPP_v1.1 OOP

    155/439

    2013-2015 Margit ANTAL

    Subclass Buper{pu4lic$ virtual voidmethod1();;class Bu($ pu4lic Buper{

    pu4lic$ virtual voidmethod2();;

    Muper 2 p9 new Muper();pI>method1(); //!

    p 9 new Mu4();pI>method1(); //!

    pI>method2(); //9C !((Mu4 2)p)I>method2();//!

    OOP. Object re%ationships

    The is-are%ationship < 0ub-class1s vie#

    the Mu4c%ass augments the Muperc%ass b&adding additiona% methods

    Super

  • 7/23/2019 CPP_v1.1 OOP

    156/439

    2013-2015 Margit ANTAL

    adding additiona% methods

    the Mu4c%ass ma& o2erride the Muperc%ass methods

    the subc%ass can use a%% the pub%icand

    protectedmembers of a superc%ass Sub

    OOP. Object re%ationships

    The is-are%ationship.preventing inheritance C++11

    &inal c%asses < cannot be e5tended

  • 7/23/2019 CPP_v1.1 OOP

    157/439

    2013-2015 Margit ANTAL

    class Buper #"nal{

    ;

    OOP. Object re%ationships

    The is-are%ationship. a client)s vie# of overridden methods(

    polymorphism Muper super;super.method5(); //Muper$$method5()

  • 7/23/2019 CPP_v1.1 OOP

    158/439

    2013-2015 Margit ANTAL

    class Buper{pu4lic$

    "rtualvoidmethod1();

    ;class Bu($ pu4lic Buper{pu4lic$

    "rtual voidmethod1();;

    Mu4 su4;su4.method5(); //Mu4$$method5()

    Buper*re& 9super;re&.method5(); //Buper::method1$%5

    re& 9 su4;re&.method5(); //Bu(::method1$%5

    Buper?ptr 9Gsuper;ptrI>method5(); //Buper::method1$%5

    ptr 9 Gsu4;ptrI>method5(); //Bu(::method1$%5

    OOP. Object re%ationships

    The is-are%ationship. a client)s vie# of overridden methods(/

    object s%icing

    class Buper{ Bu( su4;

  • 7/23/2019 CPP_v1.1 OOP

    159/439

    2013-2015 Margit ANTAL

    class Buper{pu4lic$

    "rtualvoidmethod1();;class Bu($ pu4lic Buper{

    pu4lic$"rtual voidmethod1();;

    Bu(su4;Bupersuper 9 su4;super.method5(); // Muper$$method5();

    Sub

    SuperSuper

    super sub

    OOP. Object re%ationships

    The is-are%ationship.preventing method overriding C++11

    class Buper{

  • 7/23/2019 CPP_v1.1 OOP

    160/439

    2013-2015 Margit ANTAL

    class Buper{pu4lic$

    "rtualvoidmethod1() #"nal5;class Bu($ pu4lic Buper{

    pu4lic$"rtual voidmethod1();//&''';

    OOP. Object re%ationships

    Inheritance for po%&morphism

  • 7/23/2019 CPP_v1.1 OOP

    161/439

    2013-2015 Margit ANTAL

    ///ja2atutoria%hubcom

    OOP. Object re%ationships

    The has-are%ationship

  • 7/23/2019 CPP_v1.1 OOP

    162/439

    2013-2015 Margit ANTAL

    (utton$indo/

    OOP. Object re%ationships

    Imp%ementing the has-are%ationship

    n object has an object

    (

    class Q; class Q;class Q;

  • 7/23/2019 CPP_v1.1 OOP

    163/439

    2013-2015 Margit ANTAL

    class Q;

    classM{private$

    Q4;;

    class Q;

    classM{private$

    Q*4;;

    class Q;

    classM{private$

    Q?4;;

    OOP. Object re%ationships

    Imp%ementing the has-are%ationship

    n object has an object

    strong containment =composition>

    (

  • 7/23/2019 CPP_v1.1 OOP

    164/439

    2013-2015 Margit ANTAL

    strong containment=composition>

    class Q;

    classM{private$

    Q4;;

    Man(Nect5

    b. (

    anObject.

    OOP. Object re%ationships

    Imp%ementing the has-are%ationship

    n object has an object

    -eak containment =aggregation>

    (

  • 7/23/2019 CPP_v1.1 OOP

    165/439

    2013-2015 Margit ANTAL

    -eak containment=aggregation>

    class Q;

    classM{private$

    Q*4;pu4lic$

    M$ const Q*p(%:($p(%47;

    Q4Q4Aect;MaQ4Aect5(4Q4Aect);

    MaQ4Aect6(4Q4Aect);

    aObject0.

    bObject. (

    aObject:.

    OOP. Object re%ationships

    Imp%ementing the has-are%ationship

    n object has an object

    (

    -eak containment strong containment

  • 7/23/2019 CPP_v1.1 OOP

    166/439

    2013-2015 Margit ANTAL

    class Q;

    classM{

    private$Q?4;pu4lic$

    M$%4( = new Q$%5

    7 DM$%4

    delete (57

    ;

    class Q;

    classM{

    private$Q?4;pu4lic$

    M$ Q?p(%:($ p( %47;

    -eak containment strong containment

    OOP. Object re%ationships

    Imp%ementing the has-are%ationship

    n object has an object

    (

    -eak containment

  • 7/23/2019 CPP_v1.1 OOP

    167/439

    2013-2015 Margit ANTAL

    Jsage:Q4Q4Aect;MaQ4Aect5(G4Q4Aect);MaQ4Aect6(G4Q4Aect);

    class Q;

    classM{

    private$Q?4;pu4lic$

    M$ Q?p(%:($ p( %47;

    -eak containment

    aObject0.

    bObject. (

    aObject:.

    OOP. Object re%ationships

    Imp%ementing the has-are%ationship

    n object has an object

    (

    strong containment

  • 7/23/2019 CPP_v1.1 OOP

    168/439

    2013-2015 Margit ANTAL

    class Q;

    classM{private$

    Q?4;pu4lic$

    M$%4( = new Q$%5

    7 DM$%4

    delete (57

    ;

    g

    b. (

    anObject.

    Jsage:MaQ4Aect;

    OOP. Object re%ationships

    Combining the is-aand the has-are%ationships

    class 1lass

  • 7/23/2019 CPP_v1.1 OOP

    169/439

    2013-2015 Margit ANTAL

    + 'peration(

    + d d( " Co mpon en t

    + Remo2e89 . Compon ent

    + GetChi%d89 . Compon ent

    1lient

    Lea(

    + 'peration(

    1omposite

    + Operation89

    fora%% g in chi%dren

    gOperation89Q

    + dd89 . Compone nt

    + Remo2e89 . Compone nt

    + GetChi%d89 . Compon ent

    -chi%dren

    0L

    Composite 4esign Patternclass 1lass

  • 7/23/2019 CPP_v1.1 OOP

    170/439

    2013-2015 Margit ANTAL

    Lea(

    + 'peration(

    1omposite

    + Operation89

    fora%% g in chi%dren

    gOperation89Q

    + dd89 . Compone nt

    + Remo2e89 . Compon ent

    + GetChi%d89 . Compone nt

    -chi%dren

    Compose objects into tree structures to representpart?-!ole!ierarc!ies.

    Lets c%ients treat in'ivi'ual o)*ectsand composition o( o)*ects

    uni(orml&.

    Composite 4esign Pattern

    )5amp%es. Menu MenuItem:Menus that contain menu items, each of which could be a

    menu.

  • 7/23/2019 CPP_v1.1 OOP

    171/439

    2013-2015 Margit ANTAL

    Container lement:Containers that contain lements, each of which could be a

    Container.

    "I Container "I com#onent:"I containers that contain "I com#onents,

    each of which could be a container

    %ource:http.AA///oodesigncomAcomposite-patternhtm%

    Pri2ate Inheritance

    another possibi%it& for has-are%ationship

    (ase c%ass (ase c%ass pub%icpub%ic

  • 7/23/2019 CPP_v1.1 OOP

    172/439

    2013-2015 Margit ANTAL

    4eri2ed c%ass 4eri2ed c%ass

    pub%icinheritance

    pri2ateinheritance

    pub%ic pri2ate

    4eri2ed c%assin!eritsthebase c%ass beha2ior

    4eri2ed c%ass !i'esthebase c%ass beha2ior

    Pri2ate Inheritance

    template classyBtack$pr"ate vector {

    pu4lic$ voidpush(S elem) { thisI>push14ac(elem);

    $h& ispu)lic in!eritance

    in this case dangerous

  • 7/23/2019 CPP_v1.1 OOP

    173/439

    2013-2015 Margit ANTAL

    4ool "s&mpty() { return thisI>empt(); voidpop() {

    i& (3thisI>empt())thisI>pop14ac(); S top() { i& (thisI>empt()) throw out1o&1range(*Mtac is empt*); else return thisI>4ac(); ;

    on-pub%ic Inheritance

    it is 2er& rareQ

    it ti %

  • 7/23/2019 CPP_v1.1 OOP

    174/439

    2013-2015 Margit ANTAL

    use it cautious%&Q

    most programmers are not fami%iar /ith itQ

    $hat does it print

    class Buper{pu4lic$

    Muper(){virtual void someethod(dou4le d) const{

    cout

  • 7/23/2019 CPP_v1.1 OOP

    175/439

    2013-2015 Margit ANTAL

    ;class Bu($ pu4lic Buper{pu4lic$

    Mu4(){virtual void someethod(dou4le d){

    cout

  • 7/23/2019 CPP_v1.1 OOP

    176/439

    2013-2015 Margit ANTAL

    ;class Bu($ pu4lic Buper{pu4lic$

    Mu4(){

    virtual void someethod(dou4le d){ cout

  • 7/23/2019 CPP_v1.1 OOP

    177/439

    2013-2015 Margit ANTAL

    ;class Bu($ pu4lic Buper{pu4lic$

    Mu4(){

    virtual void someethod(dou4le d) const oerr"de{ cout

  • 7/23/2019 CPP_v1.1 OOP

    178/439

    2013-2015 Margit ANTAL

    class 1lass

  • 7/23/2019 CPP_v1.1 OOP

    179/439

    2013-2015 Margit ANTAL

    "a)la

    - ce%% a3. char 8N M \ PN M \ P9

    - counte r. int

    - osE%op. int

    - sor. in t

    + getCe%%a8int! int9 . char

    + getCoun ter89 . int

    + getOsE%op89 . int Huer&J

    + getSo r89 . int Huer&J

    + printTab%a8ostream'9 . 2oid Huer&J

    + setCe%% a8int! int! char9 . 2oid

    + Tab %a8int! int9

    + tor%es89 . 2oid

    + ures)8int! int9 . boo%

    Zfriend[

    + operato rVV8ostream' ! Ta b%a '9 . ostream '

    -tab%a

    -tab%a

    Modu%e =

    Generic Programming. Temp%ates

  • 7/23/2019 CPP_v1.1 OOP

    180/439

    2013-2015 Margit ANTAL

    Generic Programming. Temp%ates

    Out%ine

    Temp%ates C%ass temp%ate

    Function temp%ate

  • 7/23/2019 CPP_v1.1 OOP

    181/439

    2013-2015 Margit ANTAL

    Temp%ate metaprogramming

  • 7/23/2019 CPP_v1.1 OOP

    182/439

    2013-2015 Margit ANTAL

    Temp%ates

  • 7/23/2019 CPP_v1.1 OOP

    183/439

    2013-2015 Margit ANTAL

    Temp%ates

    !ttp:@@---.stroustrup.com@

    Temp%ates

    %%o/ generic programming to /rite code that can /or3 /ith a%% 3ind of objects

    http://www.stroustrup.com/http://www.stroustrup.com/
  • 7/23/2019 CPP_v1.1 OOP

    184/439

    2013-2015 Margit ANTAL

    template programmerAs o)ligation:specif& there,uirements of the classes that define these objects

    template userAs o)ligation:supp%&ing those operatorsand methods that the temp%ate programmer reHuires

    Function Temp%ate

    %%o/s /riting (unction (amilies

    templatetypename C,const C max$const C* xA const C* y% 4

    return x y P y : x57

    Temp%ateparameter

  • 7/23/2019 CPP_v1.1 OOP

    185/439

    2013-2015 Margit ANTAL

    7

    templateclass C,const C max$const C* xA const C* y% 4

    return x y P y : x57

    $hat are the reHuirements regarding the t&pe T

    Function Temp%ate

    templateclass C,const C max$const C* xA const C* y% 4return x y P y : x5

    7

  • 7/23/2019 CPP_v1.1 OOP

    186/439

    2013-2015 Margit ANTAL

    ReHuirements regarding the t&pe T.

    less operator (

  • 7/23/2019 CPP_v1.1 OOP

    187/439

    2013-2015 Margit ANTAL

    ?sage. cout

  • 7/23/2019 CPP_v1.1 OOP

    188/439

    2013-2015 Margit ANTAL

    ReHuirements regarding the t&pe T. cop constructor

    assignment operator

    y = tmp57

    Function Temp%ate

    %%o/s /riting (unction (amilies

    pol&morp!ism: compile time

    1o/ the compi%er processes temp%ates

  • 7/23/2019 CPP_v1.1 OOP

    189/439

    2013-2015 Margit ANTAL

    cout

  • 7/23/2019 CPP_v1.1 OOP

    190/439

    2013-2015 Margit ANTAL

    #or $s")et " = 05 " s")e5 "++% 4"# $arr["] == alue% 4

    return "577return M65

    7

    C%ass Temp%ate

    %%o/ /riting class (amilies

    templateclass rra {

    S2 elements;

  • 7/23/2019 CPP_v1.1 OOP

    191/439

    2013-2015 Margit ANTAL

    S elements; int si8e;

    pu(l"c$ expl"c"t rra(const "nt si8e); ...;

    C%ass Temp%ate

    Temp%ate c%asss method definition

    templateclass rra { S2 elements; int si8e;

  • 7/23/2019 CPP_v1.1 OOP

    192/439

    2013-2015 Margit ANTAL

    pu(l"c$ expl"c"t rra(const "nt si8e); ...;templaterra$$rra(const "ntsi8e)$si8e(si8e),

    elements(new S%si8e'){

    C%ass Temp%ate

    Temp%ate parameters

    t&pe temp%ate parameters non-t&pe temp%ate parameters

  • 7/23/2019 CPP_v1.1 OOP

    193/439

    2013-2015 Margit ANTAL

    templateclass rra {

    S2 elements; int si8e;pu(l"c$ rra(const "nt si8e); ...;

    template

  • 7/23/2019 CPP_v1.1 OOP

    194/439

    2013-2015 Margit ANTAL

    Temp%ate c%ass.

    interface + imp%ementation go in the same fi%e e g rra.h it can be a h fi%e @ usage. #include ^rra.h it can be a cpp fi%e @ usage. #include ^rra.cpp

    C%ass Temp%ate+ Function Temp%ate

    templatestructpa"r{

    typede# C1&irst1tpe; typede# C2second1tpe; C1#"rst; C2second; pair();

    3"nclude ut"l"ty,

  • 7/23/2019 CPP_v1.1 OOP

    195/439

    2013-2015 Margit ANTAL

    p (); pair(const S5G @, const S6G ); ...

    75

    template< classS5, classS6>pa"r mae1pair(const S5G @, const S6G ){ returnpa"r(@, );

    d2anced Temp%ate

    template template parameter

    template

  • 7/23/2019 CPP_v1.1 OOP

    196/439

    2013-2015 Margit ANTAL

    void push( const CG e ){ elements.push14ac( e );

    ...;

    Btack v6;

    ?sage.

    d2anced Temp%ate

    template template parameter

    template

  • 7/23/2019 CPP_v1.1 OOP

    197/439

    2013-2015 Margit ANTAL

    void push( const CG e ){ elements.push14ac( e );

    ...;

    d2anced Temp%ate

    $hat does it do&

    template

  • 7/23/2019 CPP_v1.1 OOP

    198/439

    2013-2015 Margit ANTAL

    cout

  • 7/23/2019 CPP_v1.1 OOP

    199/439

    2013-2015 Margit ANTAL

    4ool l"nsearch( S2 &irst, S2 last, const SG what);

    template 4ool("narysearch( S2 &irst, S2 last, const SG what);

    More d2anced Temp%ate

    Temp%ate Metaprogramming

    template struct Bact{stat"c const uns"gned long "ntvalue 9 K 2 Bact$$value;

    ;t l t t t B t

  • 7/23/2019 CPP_v1.1 OOP

    200/439

    2013-2015 Margit ANTAL

    template struct Bact

  • 7/23/2019 CPP_v1.1 OOP

    201/439

    2013-2015 Margit ANTAL

  • 7/23/2019 CPP_v1.1 OOP

    202/439

    2013-2015 Margit ANTAL

    lean'er %tepanov

    https.AA///sgicomAtechAst%Adrdobbs-inter2ie/htm%

    Out%ine

    Containers

    %gorithms

    It t

    https://www.sgi.com/tech/stl/drdobbs-interview.htmlhttps://www.sgi.com/tech/stl/drdobbs-interview.html
  • 7/23/2019 CPP_v1.1 OOP

    203/439

    2013-2015 Margit ANTAL

    Iterators

    STL < Genera% Die/

    %ibrar& of reusable components

    a support for C++ de2e%opment

    b d i i

  • 7/23/2019 CPP_v1.1 OOP

    204/439

    2013-2015 Margit ANTAL

    based on generic programming

    STL < Genera% Die/

    ontainers< Temp%ate C%ass genera%iEed data structures 8&ou can use them for an&

    t&pe9

  • 7/23/2019 CPP_v1.1 OOP

    205/439

    2013-2015 Margit ANTAL

    lgorit!ms< Temp%ate Function

    genera%iEed a%gorithms 8&ou can use them for a%most an&data structure9

    Bterators< G%uebet/een Containers and %gorithms

    specifies a position into a container 8genera%iEed pointer9

    permits tra2ersa% of the container

    (asic STL Containers

    %euence containers %inear arrangement

    ectorA deSueA l"st ector, deSue, l"st,

    ector, deSue, l"st,Container

  • 7/23/2019 CPP_v1.1 OOP

    206/439

    2013-2015 Margit ANTAL

    stackA SueueA pr"or"tySueue

    ssociative containers pro2ide fast retrie2a% of data based on 3e&s

    setA mult"setA mapA mult"map set, map,

    stack, Sueue,Containeradapters

    SeHuence Containers

  • 7/23/2019 CPP_v1.1 OOP

    207/439

    2013-2015 Margit ANTAL

    ssociati2e Containers

  • 7/23/2019 CPP_v1.1 OOP

    208/439

    2013-2015 Margit ANTAL

    STL Containers C++00

    %euence containers array 8C-st&%e arra&9

    #orwardl"st8sing%& %in3ed %ist9

    i ti t i

    array, #orward-l"st,

    unordered set,

    array, #orwardl"st,

  • 7/23/2019 CPP_v1.1 OOP

    209/439

    2013-2015 Margit ANTAL

    ssociative containers

    unorderedsetA unorderedmult"set 8hash tab%e9

    unorderedmapA unorderedmult"map 8hash tab%e9

    unorderedset,unorderedmap,

    STL Containers

    homogeneous. vector, vector

    po%&morphism

  • 7/23/2019 CPP_v1.1 OOP

    210/439

    2013-2015 Margit ANTAL

    vector

    class Xerson{;class -mploee$ pu4lic Xerson{;class anager $ pu4lic -mploee{;

    STL Containers

    Person Person Person

    ectorerson,

    ectorerson,

    homogenous

  • 7/23/2019 CPP_v1.1 OOP

    211/439

    2013-2015 Margit ANTAL

    STL Containers

    Person Person Person

    ectorerson,

    ectorerson,

    ectorerson ?,

    homogenous

  • 7/23/2019 CPP_v1.1 OOP

    212/439

    2013-2015 Margit ANTAL

    Person )mp%o&ee Manager

    homogenous

    heterogenous

    The vectorcontainer - constructors

    ectorC, 5

    //empt vector

    ectorC, $nA alue%5//vector with n copies o& value

    t C, $ %

  • 7/23/2019 CPP_v1.1 OOP

    213/439

    2013-2015 Margit ANTAL

    ectorC, $n%5

    //vector with n copies o& de&ault &or S

    The vectorcontainer < add ne/ e%ements

    ector"nt, 5

    #or$ "nt "=15 "=E5 ++"%4.push(ack$ " %5

    7

    v en'=>v )egin=>

  • 7/23/2019 CPP_v1.1 OOP

    214/439

    2013-2015 Margit ANTAL

    0 : " *

    v.en'=>v.)egin=>

    The vectorcontainer

    ector"nt, $10%5cout.s")e$%endl5//PPP

    #or$ "nt "=05 ".s")e$%5 ++" %4cout[ " ]endl5

    7

    #or$ "nt "=05 "105 ++"%4.push(ack$ " %5

    7

  • 7/23/2019 CPP_v1.1 OOP

    215/439

    2013-2015 Margit ANTAL

    7cout.s")e$%endl5//PPP

    typede# ector"nt,::"terator@ectt5#or$ @ectt "t = .(eg"n$%5 "t = .end$%5 ++"t %4cout?"tendl5

    7

    The vectorcontainer. t&pica% errors

    2ind the error and correct it3

    ector"nt, 5cout.s")e$%endl5//PPP#or$ "nt "=05 "105 ++" %4

    [ " ] = "57

  • 7/23/2019 CPP_v1.1 OOP

    216/439

    2013-2015 Margit ANTAL

    cout.s")e$%endl5//PPP

    #or$ "nt "=05 ".s")e$%5 ++" %4cout[ " ]endl57

    The vectorcontainer. capacitand si8e

    ector"nt, 5.resere$ 10 %5

    cout .s")e$% endl5//PPPcout .capac"ty$% endl5//PPP

  • 7/23/2019 CPP_v1.1 OOP

    217/439

    2013-2015 Margit ANTAL

    The vectorcontainer. capacitand si8e

    ector"nt, 5.resere$ 10 %5

    cout .s")e$% endl5//PPPcout .capac"ty$% endl5//PPP

    --------------------------------------

    ector"nt, gy$ 2EI %5 Purpose

  • 7/23/2019 CPP_v1.1 OOP

    218/439

    2013-2015 Margit ANTAL

    ector"nt, gy$ 2EI %5"#stream "#s$>s)oeg.txt>%5 "nt c5

    wh"le$ $c = "#s.get$% % = -1 %4 gy[ c ]++57

    Purpose

    The vector- inde5ing

    "nt ax = 1005ector"nt, $ax%5

    //PPP...#or $"nt " = 05 " 2?ax5 "++% 4cout [ " ]T T5

    7--------------------------------------

    100

  • 7/23/2019 CPP_v1.1 OOP

    219/439

    2013-2015 Margit ANTAL

    "nt ax = 1005

    ector"nt, $ax%5#or $"nt " = 05 " 2?ax5 "++% 4

    cout .at$ " %T T57

    The vector- inde5ing

    "nt ax = 1005ector"nt, $ax%5

    //PPP...#or $"nt " = 05 " 2?ax5 "++% 4cout [ " ]T T5

    7--------------------------------------

    " t 100

    )fficient

  • 7/23/2019 CPP_v1.1 OOP

    220/439

    2013-2015 Margit ANTAL

    "nt ax = 1005

    ector"nt, $ax%5#or $"nt " = 05 " 2?ax5 "++% 4

    cout .at$ " %T T57

    Safe

    out1o&1rangee5ception

    The listcontainer

    doub%& %in3ed %ist

    l"st"nt, l5#or$ "nt "=15 "=E5 ++"%4

    l.push(ack$ " %57

  • 7/23/2019 CPP_v1.1 OOP

    221/439

    2013-2015 Margit ANTAL

    0 : " *

    l.en'=>l.)egin=>

    The deWuecontainer

    doub%e ended 2ector

    deSue"nt, l5#or$ "nt "=15 "=E5 ++"%4

    l.push#ront$ " %57

  • 7/23/2019 CPP_v1.1 OOP

    222/439

    2013-2015 Margit ANTAL

    %gorithms - sort

    template class 'andomMccessteratorA class ompare,

    o"d sort$'andomMccessterator #"rstA'andomMccessterator lastA

    ompare comp%5

    template class'andomMccessterator,

    o"d sort ('andomMccessterator #"rstA'andomMccessterator last%5

  • 7/23/2019 CPP_v1.1 OOP

    223/439

    2013-2015 Margit ANTAL

    /hat to sort. +(irstC last>

    ho/ to compare the e%ements.

    7

    comp

    %gorithms - sort

    struct 'ec 4

    string name;

    string addr;

    ;

    vector

  • 7/23/2019 CPP_v1.1 OOP

    224/439

    2013-2015 Margit ANTAL

    sort(vr.4egin(), vr.end(), mp(yname$%);

    sort(vr.4egin(), vr.end(),mp(yaddr$%);

    %gorithms - sort

    struct mp(yname4(ool operator$%(const 0ecG a, const 0ecG 4) const

    {return a.name < 4.name;

    75struct mp(yaddr4(ool operator$%(const 0ecG a, const 0ecG 4) const

    function object

  • 7/23/2019 CPP_v1.1 OOP

    225/439

    2013-2015 Margit ANTAL

    {return a.addr < 4.addr;

    75

    Strateg& 4esign Patternclass ceepusDiterator

    1onte2t

    + Conte5tInterface89

    Strategy

    + l go rit hm4nt erf ace(

    1oncrete%trateg&0

    + %gorithmInterface89

    1oncrete%trateg&

    + %gorithmInterface89

    1oncrete%trateg&1

    + %gorithmInterface89

    +strateg&

  • 7/23/2019 CPP_v1.1 OOP

    226/439

    2013-2015 Margit ANTAL

    4efine a (amil& o( algorit!ms! encapsu%ate each one! and ma3e theminterchangeab%e

    Strateg& lets t!e algorit!m var&independent%& from c%ients that use it

    Strateg& 4esign Patternclass ceepusDiterator

    1onte2t

    + Conte5tInterface89

    Strategy

    + l go rit hm4nt erf ace(

    1oncrete%trateg&0

    + %gorithmInterface89

    1oncrete%trateg&

    + %gorithmInterface89

    1oncrete%trateg&1

    + %gorithmInterface89

    +strateg&

    sort

  • 7/23/2019 CPP_v1.1 OOP

    227/439

    2013-2015 Margit ANTAL

    4efine a (amil& o( algorit!ms! encapsu%ate each one! and ma3e theminterchangeab%e

    Strateg& lets t!e algorit!m var&independent%& from c%ients that use it

    Strateg& 4esign Patternclass ceepusDiterator

    1onte2t

    + Conte5tInterface89

    Strategy

    + l go rit hm4nt erf ace(

    1oncrete%trateg&0

    + %gorithmInterface89

    1oncrete%trateg&

    + %gorithmInterface89

    1oncrete%trateg&1

    + %gorithmInterface89

    +strateg&

    sortboo% operator898

    const T'!const T'9

  • 7/23/2019 CPP_v1.1 OOP

    228/439

    2013-2015 Margit ANTAL

    4efine a (amil& o( algorit!ms! encapsu%ate each one! and ma3e theminterchangeab%e

    Strateg& lets t!e algorit!m var&independent%& from c%ients that use it

    Strateg& 4esign Patternclass ceepusDiterator

    1onte2t

    + Conte5tInterface89

    Strategy

    + l go rit hm4nt erf ace(

    1oncrete%trateg&0

    + %gorithmInterface89

    1oncrete%trateg&

    + %gorithmInterface89

    1oncrete%trateg&1

    + %gorithmInterface89

    +strateg&

    sortboo% operator898

    const T'!const T'9

  • 7/23/2019 CPP_v1.1 OOP

    229/439

    2013-2015 Margit ANTAL

    Cmpb&name Cmpb&addr

    Iterators

    Thecontainermanages the contained objects but doesnot 3no/about algorithms

    The algorithm/or3s on data but does not 3no/the

  • 7/23/2019 CPP_v1.1 OOP

    230/439

    2013-2015 Margit ANTAL

    interna% structure of containers

    4teratorsfit containers to a%gorithms

    Iterator - the glue

    "nt x[]=41A2AHAKAE75 ector"nt,$xA x+E%5"nt sum1 = accumulate$.(eg"n$%A .end$%A 0%5

    l"st"nt, l$xA x+E%5

    0 : " *

    2end892begin89

  • 7/23/2019 CPP_v1.1 OOP

    231/439

    2013-2015 Margit ANTAL

    $ A %5

    dou(le sum2 = accumulate$l.(eg"n$%A l.end$%A 0%5

    0 : " *

    %end89%begin89

    Iterator - the glue

    templateclass ntA classC,

    Caccumulate(nt&irst, ntlast, Cinit){while (&irst39last) {init 9 init + 2&irst;++&irst;

  • 7/23/2019 CPP_v1.1 OOP

    232/439

    2013-2015 Margit ANTAL

    return init;

    The setcontainer

    set!ey[A omp= less!ey,],

    usually implemented as a balanced binary search tree

    mult"set:a%%o/s dup%icates

  • 7/23/2019 CPP_v1.1 OOP

    233/439

    2013-2015 Margit ANTAL

    Source.http.AA///cpp-tutordeAcppA%e07AimagesAsetgif

    The setcontainer - usage

    3"nclude set,

    set"nt, "ntBet5

    seterson, personBet15

  • 7/23/2019 CPP_v1.1 OOP

    234/439

    2013-2015 Margit ANTAL

    setersonA ersonomp, personBet25

    The setcontainer - usage

    73"nclude set,

    set"nt, "ntBet5

    seterson, personBet15

  • 7/23/2019 CPP_v1.1 OOP

    235/439

    2013-2015 Margit ANTAL

    setersonA ersonomp, personBet25

    The setcontainer - usage

    (ool operator$const erson*A const erson*%

    73"nclude set,

    set"nt, "ntBet5

    seterson, personBet15

  • 7/23/2019 CPP_v1.1 OOP

    236/439

    2013-2015 Margit ANTAL

    setersonA ersonomp, personBet25

    The setcontainer - usage

    (ool operator$const erson*A const erson*%

    73"nclude set,

    set"nt, "ntBet5

    seterson, personBet15

  • 7/23/2019 CPP_v1.1 OOP

    237/439

    2013-2015 Margit ANTAL

    struct ersonomp4(ool operator$% $ const erson*A const erson* %5

    75

    setersonA ersonomp, personBet25

    The setcontainer - usage

    3"nclude set,

    set"nt, myBet5

    wh"le$ c"n ,, nr %4

    myBet."nsert$ nr %5

    7

  • 7/23/2019 CPP_v1.1 OOP

    238/439

    2013-2015 Margit ANTAL

    set"nt,::"terator "ter5

    #or $"ter=myBet.(eg"n$%5 "ter=myBet.end$%5 ++"ter%4

    cout ?"ter endl5

    7

    The setcontainer - usage

    set"nt,::"terator "ter5

    #or $"ter=myBet.(eg"n$%5 "ter=myBet.end$%5 ++"ter%4

    cout ?"ter endl5

    7

    ----------------------------------------------------

    #or$ auto*": myBet %4

  • 7/23/2019 CPP_v1.1 OOP

    239/439

    2013-2015 Margit ANTAL

    cout"endl5

    7

    The multisetcontainer - usage

    mult"set"nt, myBet5

    s")et nr&lements = myBet.count$12%5

    mult"set"nt,::"terator "ter5

    "ter = myBet.#"nd$10%5

  • 7/23/2019 CPP_v1.1 OOP

    240/439

    2013-2015 Margit ANTAL

    "# $"ter == myBet.end$%%4cout>Che element does not ex"st>endl5

    7

    The setcontainer - usage

    class ersonompare5

    class erson4 #r"end class ersonompare5

    str"ng #"rst9ame5

    str"ng last9ame5

    "nt year#Q"rth5

    pu(l"c:

  • 7/23/2019 CPP_v1.1 OOP

    241/439

    2013-2015 Margit ANTAL

    erson$str"ng #"rst9ameA str"ng last9ameA "nt year#Q"rth%5#r"end ostream* operator$ostream* osA const erson* person%5

    75

    The setcontainer - usage

    class ersonompare 4

    pu(l"c:

    enum r"ter"on 4 9M&A Q'C

  • 7/23/2019 CPP_v1.1 OOP

    242/439

    2013-2015 Margit ANTAL

    sw"tch $cr"ter"on% 4

    case 9M&: //

    case Q'C

  • 7/23/2019 CPP_v1.1 OOP

    243/439

    2013-2015 Margit ANTAL

    cout pendl5

    7 EE2011

    The setcontainer - usage

    setersonA ersonompare, s$ ersonompare::9M&%5 s."nsert$erson$>Q"ro>A >stan>A 1UI0%%5

    s."nsert$erson$>M(os>A >6ergely>A 1UVI%%5

    s."nsert$erson$>6ered>A>Mtt"la>A 1UVI%%5

    ----------------------------------------------------

    #or$ auto*p: s%4

  • 7/23/2019 CPP_v1.1 OOP

    244/439

    2013-2015 Margit ANTAL

    cout pendl5

    7 EE2011

    The mapcontainer

    map!eyA @alue[Acomp= less!ey,],

    usually implemented as a balanced binary treemult"map:a%%o/s dup%icatesmap:associati2e arra&

  • 7/23/2019 CPP_v1.1 OOP

    245/439

    2013-2015 Margit ANTAL

    Source. http.AA///cpp-tutordeAcppA%e07AimagesAmapgif

    The mapcontainer - usage

    3"nclude map,

    mapstr"ngA"nt, products5

    products."nsert$makepa"r$>tomato>A10%%5

    ----------------------------------------------

    products[>cucum(er>]= I5

  • 7/23/2019 CPP_v1.1 OOP

    246/439

    2013-2015 Margit ANTAL

    coutproducts[>tomato>]endl5

    The mapcontainer - usage

    3"nclude map,

    mapstr"ngA"nt, products5

    products."nsert$makepa"r$>tomato>A10%%5

    ----------------------------------------------

    products[>cucum(er>]= I5

  • 7/23/2019 CPP_v1.1 OOP

    247/439

    2013-2015 Margit ANTAL

    coutproducts[>tomato>]endl54ifference bet/een

    + ,and insert///

    The mapcontainer - usage

    typede#mapstr"ngA"nt,::"teratorapt5#or$apt"t=aruk.(eg"n$%5 "t = aruk.end$%5 ++"t%4 cout$"t-,#"rst%> : >$"t-,second%endl57

  • 7/23/2019 CPP_v1.1 OOP

    248/439

    2013-2015 Margit ANTAL

    --------------------------------------------------#or$auto* ": aruk %4 cout$".#"rst%> : >$".second%endl57

    C++:;00

    The multimapcontainer - usage

    mult"mapstr"ngA str"ng, c"t"es5

    c"t"es."nsert$makepa"r$>J>A >Qudapest>%%5 c"t"es."nsert$makepa"r$>J>A >B)eged>%%5 c"t"es."nsert$makepa"r$>'>A >Bekler(urg>%%5 c"t"es."nsert$makepa"r$>'>A >9eumarkt>%%5 c"t"es."nsert$makepa"r$>'>A >ermannstadt>%%5

    typede# mult"mapstr"ng str"ng,::"terator C5" C C, t "t" l $>J>%

  • 7/23/2019 CPP_v1.1 OOP

    249/439

    2013-2015 Margit ANTAL

    typede#mult"mapstr"ngA str"ng,::"teratorC5 pa"rCA C, ret = c"t"es.eSualrange$>J>%5 #or $C "t = ret.#"rst5 "t = ret.second5 ++"t% 4 cout $?"t%.#"rst >Wt>$?"t%.secondendl5 7

    The multimapcontainer - usage

    mult"mapstr"ngA str"ng, c"t"es5

    c"t"es."nsert$makepa"r$>J>A >Qudapest>%%5 c"t"es."nsert$makepa"r$>J>A >B)eged>%%5 c"t"es."nsert$makepa"r$>'>A >Bekler(urg>%%5 c"t"es."nsert$makepa"r$>'>A >9eumarkt>%%5 c"t"es."nsert$makepa"r$>'>A >ermannstadt>%%5

    typede# mult"mapstr"ng str"ng,::"terator C5pa"rC C, ret = c"t"es eSual range$>J>%5

    mu%timaps do not pro2ideoperator+ ,W!&

  • 7/23/2019 CPP_v1.1 OOP

    250/439

    2013-2015 Margit ANTAL

    typede#mult"mapstr"ngA str"ng,::"teratorC5 pa"rCA C, ret = c"t"es.eSualrange$>J>%5 #or $C "t = ret.#"rst5 "t = ret.second5 ++"t% 4 cout $?"t%.#"rst >Wt>$?"t%.secondendl5 7

    The set/mapcontainer - remo2a%

    o"d erase $ "ter