40931 Lecture05-Operator Overloading and Exception Handling

download 40931 Lecture05-Operator Overloading and Exception Handling

of 37

Transcript of 40931 Lecture05-Operator Overloading and Exception Handling

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    1/37

    Operator Overloading &Exception Handling

    TCP1201 OOPDS 1

    Lecture 5

    1

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    2/37

    Learning Objectives

    Operator Overloading

    To understand what is operator overloading To understand the advantage of operator overloading

    To understand how to overload operators as functions

    Exception handling

    To understand what is exception To realize the advantages of exception handling

    To understand the use of try, throw and catch block

    To understand how exception propagation works

    To understand how to wrote multiple catch blocks andexception matching

    2

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    3/37

    Operator Overloading

    Add capability to an operator via writing a new "special

    function" for the same operator but with different datatypes and combinations of parameters.

    For example, C++s operator +!

    C++ has builtin support for using operator + to add

    int

    or double, and also for concatenating string. #owever using operator + to add $ ob%ects of your

    &userdefined' class is not automatically supported.

    (e can write a "function" to ma)e C++ support

    adding $ ob%ects of userdefined class. *his processis called operator overloading.

    3

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    4/37

    Operator Overloading Advantage It provides a simplerway for doing some

    operations on user-dened classes.

    Consider the following Rationalclass whichrepresents a rationalfraction number, e.g. $, $-!

    class Rational {

    int num; // numerator

    int den; // denominatorpublic:

    Rational (int num=0, int den=1) : num(num), den(den) {}

    int getNum() { return num; }

    int getDen() { return den; }

    };

    Rationalmultipl(Rational! r1, Rational! r") {

    int n = r1#getNum() $ r"#getNum(); int d = r1#getDen() $ r"#getDen();

    return Rational (n, d);

    }

    4

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    5/37

    *o multiply rational numbers e.g. $ - /0 1

    /-0, we can use the method multiply(), but it

    loo)s more complex.

    2f we overload multiply operator , we can write!

    int main() {

    Rational r1(1,"), r"(1,%), r%(&,'), r;

    r = multipl(r1, multipl(r",r%));

    ###

    int main() {

    Rational r1(1,"), r"(1,%), r%(&,'), r; r = r1 $ r" $ r%;

    ###

    Complex

    Simple &easy to

    understand

    Operator Overloading Advantage

    5

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    6/37

    Operators in C++ are divided into 2 categories based

    on the number of arguments they accept: Unaryoperators accept one argument

    x++, --x, !x, etc.

    Binaryoperators accept two arguments x+y, x-y, x*y, x

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    7/37

    3ome unary operators can be used as both prefix and postfix

    operators, e.g. increment 4++5 and decrement 45 operators.

    int a = b = 0;

    a; // a = 1

    b = a; // b = ", a = "cout ** +a is:+ ** a; // a is "

    cout ** +b is:+ ** b; // b is "

    b = a; // b = "

    // a = %cout ** +a is:+ ** a; // a is %

    cout ** +b is:+ ** b; // b is "

    prefix

    postfix

    C++ Operators

    7

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    8/37

    (e overload an operator by writing a special function with

    the )eyword operatorS

    , whereS

    is an operator symbol &+,, , , 6, ++, etc.'.

    (e should overload an operator in a sensible way and meet

    general expectation, e.g. dont overload operator to

    perform division.

    Ho to Overload Operators!

    returntypeoperatorS(parameters){

    ###

    returnsomething;

    }

    8

    // For our Rational number multiplication.

    returntypeoperator$(parameters){

    ###

    returnsomething;

    }

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    9/37

    *he number of parameters depend whether the overloaded

    operator is unary or binary. 7naryoperator has parameter.

    8inaryoperator has $parameters.

    3ince operator is a binary operator hence the number ofparameter is $.

    (e are multiplying $ Rationalob%ects and expecting theresult is also a Rationalob%ect, hence the data type of

    both parameter and return type should be Rational.

    Ho to Overload Operators!

    9

    // For our Rational number multiplication.

    Rational operator$(Rational, Rational){

    ###

    returnRational(); // return a ne ob-ect#

    }

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    10/37

    Overloading Operator "#" as $on%riend unction

    class Rational {

    int num;

    int den;

    public:

    Rational (int num = 0, int den = 1)

    : num(num), den(den) {}

    .oid print() {

    cout ** num ** +/+ ** den ** endl;

    } int getNum() { return num; }

    int getDen() { return den; }

    };

    Rational operator$ (Rational! r1,

    Rational! r") {

    int n = r1#getNum()$ r"#getNum(); int d = r1#getDen()$ r"#getDen();

    return Rational (n, d); // Return a ne

    // Rational ob-ect

    }

    int main() {

    Rational r1(1,"),

    r"(1,%),

    r%(&,'),

    r;

    r = r1 $ r" $ r%; r1#print();

    r"#print();

    r%#print();

    r#print();

    }

    utput:1/"

    1/%

    &/'

    &/%'

    Non-friendfunction call

    methods.

    10

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    11/37

    friendAccess 'rivilege

    class Rational {

    riend Rational operator$ (Rational!, Rational!);

    int num, den;

    ###

    };

    Rational operator$ (Rational! r1, Rational! r") {

    int n = r1#num$ r"#num; // Directl access pri.ate member#

    int d = r1#den$ r"#den;

    return Rational (n, d);

    }

    If class grants a global function !not a method" oranother class # !not subclass" a friend access

    privilege$ it means that class allows the globalfunction or class # to access its private members.

    %his actually violates encapsulation but is generallyaccepted when doing operator overloading.

    friend function is not a method of the class.

    11

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    12/37

    Overloading Operator "#" as riend unction

    class Rational {

    riend Rational operator$ (Rational!,

    Rational!); int num;

    int den;

    public:

    Rational (int num=0, int den=1)

    : num(num), den(den) {}

    .oid print() { cout ** num ** +/+

    ** den ** endl;

    }

    };

    Rational operator$ (Rational! r1,

    Rational! r") {

    int n = r1#num$ r"#num;

    int d = r1#den$ r"#den;

    return Rational (n, d); // Return a ne

    // Rational ob-ect

    }

    int main() {

    Rational r1(1,"),

    r"(1,%),

    r%(&,'),

    r;

    r = r1 $ r" $ r%; r1#print();

    r"#print();

    r%#print();

    r#print();

    }

    utput:1/"

    1/%

    &/'

    &/%'

    Friend functioncan access private

    member directly.

    12

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    13/37

    istream! operator (istream! is,*2our3lass!p){

    is *code or cin;

    return is; // Return e4isting ob-ect instead o ne ob-ect#

    }

    ostream! operator** (ostream! os,*2our3lass!p) {

    os ***code or cout;

    return os; // Return e4isting ob-ect instead o ne ob-ect#

    }

    Overloading Operator "((" and "))"

    #oth insertion operator &''& and e(traction operator&))& are binaryoperators because they need 2

    arguments to wor*. *hey usually have the following pattern &return type and first

    parameter' regardless of the class you want to overload.

    9our %ob is to figure out your class and the code for cinor

    cout.

    13

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    14/37

    class Rational {

    riend istream! operator (istream!, Rational!);

    ###

    };

    istream! operator (istream! is, Rational! r){

    is r#num r#den;

    // r#getNum() ! r#getDen() on5t or6#789

    return is;

    }

    ostream! operator** (ostream! os,

    Rational! r){ os ** r#getNum() ** +/+ ** r#getDen();

    return os;

    }

    int main() {

    Rational r1,

    r",

    r%;

    cin r1

    r";r% = r1 $ r";

    cout** r1**endl

    ** r"**endl

    ** r%;

    }

    utput:1 " %

    1/"

    %/

    %/

    Overloading Operator "((" and "))"

    Overloading &''& and &))& allows us to use them onobect of user-dened class.

    14

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    15/37

    'arameters & *eturn ypes

    ,or parameters$ use references whenever possible

    !especially when the parameter is a big obect". lways try to follow the spirit of the built-in

    implementations$ e.g. comparison operators !==$ !=$>$ etc" generally return abool$ so an overloaded

    version should do the same.

    15

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    16/37

    ,ncrement Operator "++"

    Is a unary operator that can be used as both a pre( !++(" and post( !(++" operator.

    ow does compiler *now whether we are overloadingpre( or post(

    /se our Rational class as e(ample:

    %he function prototype for overloadpre(operator:

    %he function prototype for overloading post(operator:

    0ost( re1uires int parameter to di3erentiate

    itself from pre(.

    Rational operator(Rational !)//prei4

    Rational operator(Rational !, int)//posti4

    16

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    17/37

    class Rational {

    ###

    };

    bool operator* (Rational! r1, Rational! r"){

    return r1#getNum()$r"#getDen()*r1#getDen()$r"#getNum();}

    int main() {Rational r1(1,"), r"(",%), r%(1,");i (r1*r") cout ** +r1 is smaller t8an r"n+;else cout ** +r1 is N< smaller t8an r"n+;

    i (r1*r%) cout ** +r1 is smaller t8an r%n+;else cout ** +r1 is N< smaller t8an r%n+;}

    utput:r1 is smaller t8an r"r1 is N< smaller t8an r%

    Overloading Operator "("#inary operator &'& is for comparing 2 arguments.ence it should return a #oolean result.

    17

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    18/37

    include *algorit8m // sort()

    ###

    class >oint {

    int 4, ;

    public:

    >oint (int 4 = 0, int = 0) : 4(4), () { }

    int get?() { return 4; }

    int get2() { return ; }

    };ostream! operator** (ostream! os, >oint! p) {

    os ** +(+ ** p#get?() ** +, + ** p#get2() ** +)+;

    return os;

    }

    class @ortA? {

    public:

    bool operator()(>oint p1, >oint p") { return p1#get?() * p"#get?(); }

    };

    class @ortA2 {

    public:

    bool operator() (>oint p1, >oint p")

    { return p1#get2() * p"#get2(); }

    };

    int main() {

    >oint ptsB%C =

    {>oint(%,'),

    >oint(&,),

    >oint(1,")};

    or (int i=0; i*%; i)

    cout ** ptsBiC ** + +;

    cout ** endl;

    sort (pts, pts%, @ortA?());

    or (int i=0; i*%; i)

    cout ** ptsBiC ** + +;

    cout ** endl;

    sort (pts, pts%,

    @ortA2());

    or (int i=0; i*%; i)

    cout ** ptsBiC ** + +;}

    utput:

    (%, ') (&, ) (1, ")

    (1, ") (%, ') (&, )

    (1, ") (&, ) (%, ')

    Overloading Operator "-."To sort an array or vector of your class by dierentattribute at dierent time.

    18

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    19/37

    /xception Handling

    (hen a program is executed, unexpected situations may

    occur. 3uch situations are called exceptions.2n other word! An exceptionis a runtime error caused by

    some abnormal conditions.

    :xample!

    ;ivision by

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    20/37

    /xception /xample0 1ivision 2y 3ero

    double di.ide (double 4, double ) {

    return 4 / ; // di.ide b 0 i = 0

    }

    int main() {

    double 4, ;

    cin 4 ;

    cout ** +Result = + ** di.ide (4, );

    }

    Ho to deal it4 t4e error belo!

    20

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    21/37

    /xception /xample0 1ivision 2y 3ero

    double di.ide (double 4, double ) {

    return 4 / ; // di.ide b 0 i = 0

    }

    int main() {

    double 4, ;

    cin 4 ; i( == 0) cout ** +3annot di.ide b eron+;

    else cout ** +Result = + ** di.ide (4, );

    }

    A solution is shown below. 2t wor)s but the codes that

    handles the error mixes with the codes for division, ma)ingthe codes harder to read &is ifor division and elsefor

    error handling, or the other way> ?o direct indication from

    i/else )eywords alone.

    21

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    22/37

    C++ implements exception handling using try, trowand catcbloc).

    tr bloc0 (rite the code that might generate runtime error within

    the trbloc).

    /xception Handling

    22

    tr {

    // 3ode t8at ma generate e4ceptions#

    ###

    i (*error condition is true)

    t8ro *E4ception ob-ect;

    ###}

    catc8 (*E4ception tpe) {

    // Error 8andling code#

    ###

    }

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    23/37

    t8rostatement0 7se )eyword t8roin trbloc) to signal that

    abnormal condition or error has occurred. 2f the t8rostatement is executed, the C++ runtime will

    s)ip the remaining of the trbloc), and %ump to the

    catc8bloc) to continue execution.

    tr6 t8ro6 and catc8blocs

    23

    tr {

    // 3ode t8at ma generate e4ceptions#

    ###

    i (*error condition is true)

    t8ro *E4ception ob-ect; // Fump to catc8 bloc6#

    ### //7ill be s6ipped i t8ro statement is e4ecuted#}

    catc8 (*E4ception tpe) {

    // Error 8andling code#

    ###

    }

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    24/37

    catc8bloc0 (rite the code that catches the thrown exception ob%ect

    in catc8bloc). *his is the exception handler. 7nhandled7ncaught thrown exception will terminate the

    program.

    tr6 t8ro6 and catc8blocs

    24

    tr {

    // 3ode t8at ma generate e4ceptions#

    ### i (*error condition is true)

    t8ro*E4ception ob-ect;

    ###

    }

    // No code 8ere#

    catc8 (*E4ception tpe) { //

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    25/37

    double di.ide (double 4, double ) {

    i ( == 0)

    t8ro ; return 4 / ;

    }

    int main() {

    double 4, ;

    cin 4 ;

    tr { double result = di.ide (4, );

    cout ** +Result = + ** result;

    }

    catc8 (double a) {

    cout ** +3annot di.ide b eron+;

    }}

    ,f t4ere is an exception6

    t4ro it7

    'ut code t4at may

    generate error in

    trybloc7

    ,f t4ere is no exception6resume execution7

    ,f t4ere is an exception

    of type double6

    catc4 it7

    /xample0 tr6 t8ro6 and catc8blocs

    25

    / l d bl

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    26/37

    double di.ide (double 4, double ) {

    i ( == 0)

    t8ro ; return 4 / ;

    }

    int main() {

    double 4, ;

    cin 4 ;

    tr { double result = di.ide (4, );

    cout ** +Result = + ** result;

    }

    catc8 (double a) {

    cout ** +3annot di.ide b eron+;

    }}

    utput1:No e4ception

    1 "

    Result = 0#&

    utput":7it8 e4ception

    1 0

    3annot di.ide b ero

    84en an exception is

    t4ron6 t4e codes

    t4at appear after t4et8rostatement in

    t4e trbloc is

    sipped7

    /xample0 tr6 t8ro6 and catc8blocs

    26

    / l d bl

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    27/37

    double di.ide (double 4, double ) {

    i ( == 0)

    t8ro ; return 4 / ;

    }

    int main() {

    double 4, ;

    cin 4 ;

    tr { double result = di.ide (4, );

    cout ** +Result = + ** result;

    }

    catc8 (double a) {

    cout ** +3annot di.ide b

    eron+; }

    }

    /xample0 tr6 t8ro6 and catc8blocs

    utput1:No e4ception

    1 "

    Result = 0#&

    utput":7it8 e4ception

    1 0

    3annot di.ide b ero

    4e type of t4e object

    being t4ron must

    matc4 t4e type of t4eparameter in t4e

    catc8bloc

    27

    / l d bl

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    28/37

    double di.ide (double 4, double ) {

    i ( == 0)

    t8ro ; return 4 / ;

    }

    int main() {

    double 4, ;

    cin 4 ;

    tr { double result = di.ide (4, );

    cout ** +Result = + ** result;

    }

    catc8 (int a) {

    cout ** +3annot di.ide b

    eron+; }

    }

    /xample0 tr6 t8ro6 and catc8blocs

    utput1:No e4ception

    1 "

    Result = 0#&

    utput":7it8 e4ception

    1 0

    terminate called ater

    t8roing an instanceo 5double5

    ,f t4e type of object

    being t4ron does

    not matc4 t4e type oft4e parameter in t4e

    catc8bloc6

    28

    / l 8 d 8 bl

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    29/37

    int main() {

    double 4, ;

    cin 4 ;

    tr {

    i ( == 0) t8ro ;

    double result = 4 / ;

    cout ** +Result = + ** result;

    }

    catc8 (double a) {

    cout ** +3annot di.ide b eron+; }

    }

    /xample0 tr6 t8ro6 and catc8blocs

    utput1:No e4ception

    1 "

    Result = 0#&

    utput":7it8 e4ception1 0

    3annot di.ide b ero

    ?ote that exception handling does not re=uire a function to

    wor).

    29

    / ti ' ti

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    30/37

    /xception 'ropagation

    2f the function containing the trowstatement does notcatch the exception, the exception will be propagated up to

    the callerof the function until it reaches a trybloc) or themain

    function.

    2n the former case, the trycatcbloc) of the caller

    handles the exception if the exception type matches one ofthe catcbloc). @therwise the exception will bepropagated up again.

    2f the exception reaches the mainfunction and is nothandled, the program will be terminated.

    30

    / l / ti ' ti

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    31/37

    /xample0 /xception 'ropagation

    double "(double 4, double ) {

    i ( == 0) t8ro ;

    return 4 / ;

    }double 1(double 4, double ) {

    return "(4, );

    }

    double di.ide (double 4, double ) {

    return 1(4, );

    }

    int main() {

    ###

    tr {

    double result = di.ide (4, );

    cout ** +Result = + ** result;

    }

    catc8 (double a) {

    ###

    utput:7it8 e4ception

    1 0

    3annot di.ide b ero

    4e exception is

    propagated in t4e

    folloing order0

    "()61()6di.ide()6

    main()7

    4emain()catc4es

    and 4andles t4eexception7

    31

    9 lti l t 8 2l

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    32/37

    3ometimes, we might have many different exceptions

    for a small bloc) of code.

    9ultiple catc82locs

    32

    tr{

    ###

    i (*Error1) t8ro*b-ect o e4ception tpe1;

    i (*Error") t8ro*b-ect o e4ception tpe";

    i (*Error%) t8ro*b-ect o e4ception tpe%;

    ###

    }

    catc8(*E4ceptiontpe1) {

    // 3ode t8at resol.es a tpe1 e4ception#

    }

    catc8(*E4ceptiontpe") {

    // 3ode t8at resol.es a tpe" e4ception#

    }

    catc8(*E4ceptiontpe%) {

    // 3ode t8at resol.es a tpeN e4ception#

    }

    9 ltiple t 8 2locs

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    33/37

    8ut, which catc8bloc) will be instigatedinvo)ed>;epend on the type of exception ob%ect.

    *he type must match exactly, no implicit conversion will

    be done by C++. *ype doubledoes not match with type

    int.

    @nly one catc8bloc)will be executed for an exception.

    *he catc8bloc) that first matchesthe exception type

    would be chosen.

    9ultiple catc82locs

    33

    9ultiple t 8 2locs

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    34/37

    int main () {

    unc (1);

    unc (%); unc ();

    }

    utput:

    3atc8 int 11

    3atc8 double %#&n is not 1 or %

    .oid unc (int n) {

    tr {

    i (n == 1) t8ro 11; // int i (n == %) t8ro %#&; // double

    cout ** +n is not 1 or %n+;

    }

    catc8 (double a) {// 7on5t catc8 int

    cout ** +3atc8 double + ** a ** endl;

    }catc8 (inta) { // Gatc8 int

    cout ** +3atc8 int + ** a ** endl;

    }

    }

    ?o implicit

    conversionofexception type in

    catc8argument

    9ultiple catc82locs

    34

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    35/37

    /xception 9atc4ing

    *o catch every possible exception type, use ellipsis ":".

    imitations ofcatc8 (###):

    9ou cant tell what type of exception occurred. ?o argument to reference. 3hould always be placed as the last catcbloc).

    tr {

    ###

    }

    catc8 (###) { // catc8es HII e4ception tpes#

    ### }

    35

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    36/37

    /xception 9atc4ingint main () {

    unc (1);

    unc (");

    unc (%);

    unc ();

    }

    utput:Not double nor string

    3atc8 string abc

    3atc8 double %#&

    n is not 1, " or %

    .oid unc (int n) {

    tr {

    i (n == 1) t8ro 11; // int

    i (n == ") t8ro string(+abc+);

    i (n == %) t8ro %#&; // double

    cout ** +n is not 1, " or %n+;

    }

    catc8 (doublea) {

    cout ** +3atc8 double + ** a ** endl;}

    catc8 (stringa) {

    cout ** +3atc8 string + ** a ** endl;

    }

    catc8 (###) { // all tpes

    cout ** +Not double nor stringn+;

    }

    }

    36

  • 7/25/2019 40931 Lecture05-Operator Overloading and Exception Handling

    37/37

    Advantages of /xception Handling

    7sing try, trow, and catcbloc)s to handleexception offer the following advantages!

    . Brovide clarify on the section of codes that

    handle the error.

    $. 9ou may throw an exception in afunctionmethod, and handle it somewhere else.

    37