OOP- Notes.doc

Embed Size (px)

Citation preview

  • 8/14/2019 OOP- Notes.doc

    1/190

    Session 1

    Some features of C and

    Introduction to the language C++,(Part 1)

    During this session you will learn about:

    Basic data types.

    Qualifiers.

    Variables declaration and definition and usage.

    Recursive function.

    Scope rules and Storage specifier - automatic, static, external,

    register. Control flo Branc!ing and "ooping statements.

    #!e brea$ and continue statements.

    #!e C language !as, over t!e past fe years, became one of t!emost popular programming language. #!is rapid popularity, amongstot!er reasons, can be attributed to t!e s!eer poer and simplicity oft!e languages. #!e C%% became still popular because it maintains t!esimplicity of t!e C &rogramming language and also ma$es it morepoerful by supporting t!e 'b(ect 'riented &rogramming concepts.

    #!is c!apter introduces several features of t!ese languages. )f youalready $no C or even if you !ave not learnt t!e language earlier, t!isc!apter prepares you to explore t!e language C%%.

    1.1.Literals (Constants)

    Constants are data storage locations whose address is notaccessiblefor t!e user. #!eir value is not c!anged during t!e course oft!e program.

    "iteral constant * represented by t!eir value.Symbolic constants * represented by t!eir symbols + names.

    e.g.

    sum num % /

    ++ is a literal constant.

    120

  • 8/14/2019 OOP- Notes.doc

    2/190

    ++ sum is a symbolic constant.

    Constants as ell as variables !ave types associated it! t!em.

    #!e folloing table summari0es t!e data types , t!eir si0es andt!eir range, for a 1-bit mac!ine.

    #ype Si0e in Bytes Range2nsigned s!ortint.

    3 to 14,454

    S!ort int. 3 -53,617 to 536162nsigned longint.

    8 to 8,398,916,394

    "ong int. 8 -3,86,875,187 to3,86,875,186

    int. 3 -53,617 to 53,6162nsigned int. 3 to 14,454C!ar 341 c!aracter values:loat 8 .3e-57 to 5.8e57;ouble 7 3.3e-57 to .7e57

    1.2. Integer literal

    )nteger are numbers it!out fractional parts.e.g.

    3 ++ ;ecimal38 ++ 'ctalx8 ++ .

    1.3. Floating literal

    #!ey can be ritten in common decimal as ell as scientificnotation( floating point representation). By default it is of type double.:, " are applied only to common decimal notation.

    121

  • 8/14/2019 OOP- Notes.doc

    3/190

    e.g.

    5.84: , .?-5, 3.584", 3. , 5?, ."

    1.. !oolean constants

    )t can !old 3 values true=> or false=>.

    1.". Character literal

    C!aracter literals are c!aracters , digits and some specialsymbols, !ic! are enclosed in single @uotes and re@uire a single byte

    of memory.

    e.g.

    AaA, 3A, .A, A=blan$> -uses a byte.

    1.#. S$ecial Character set ( %sca$e Se&uences)'

    !en normal c!aracters are preceded it! a D =bac$ slas!> , t!eyor$ in a different ay. #!ese are called escape se@uences.

    e.g.

    Dn ne lineDt !ori0ontal tabDv vertical tabDE double @uotes.

    #!ey can also be represented using literal constants .

    e.g.

    D8 instead of Dn for neline.

    1.. String literal'

    Fn array of constant c!aracters is represented as strings.

    122

  • 8/14/2019 OOP- Notes.doc

    4/190

    Gero or more c!aracters are represented it!in double @uotationmar$s. #!ese are terminated by a null c!aracter. #!e compiler doest!is.

    e.g.

    H E -- null stringHaEHDnccDtoptionsDtfile.IccJDnE

    H a multiline D string literal signals its D continuation it! a bac$slas!E

    1.. *ualifiers

    Fll variables by default are signed = t!e sign bit is also stored asa part of t!e number >. )f it is $non before!and t!at t!e value of avariable ill not be signed, t!en t!e $eyord unsignedcan precede avariable, t!us declaring it an unsigned variable. #!is is called as a

    qualifier.

    e.g.

    unsigned int num 58/unsigned arr 3/

    Kote t!at in t!e second example t!e data type is omitted, in!ic! case it defaults to being an integer.

    #!ere are many occasions !en values to be stored in t!e

    variable exceeds t!e storage space allocated to t!em. :or instance, aninteger on a 1-bit processor is allocated 3 bytes, !ic! can store att!e most 14454, if t!e variable is unsigned. )f a bigger number is to bestored in a variable , t!en t!e @ualifier long can be used.

    e.g.

    long int num 358548l/

    123

  • 8/14/2019 OOP- Notes.doc

    5/190

    long emp 35853"/unsigned long int ulinum /unsigned long ulnum/

    Kote t!at t!e to @ualifiers it! one variable declaration canalso be given. )n t!is case t!e last to variables can !ave double t!eamount of storage and are unsigned. Flso note t!at t!e letter "A or lAsucceeds long constants.

    Similarly, t!ere is anot!er @ualifier short, !ic! gives storagee@ual to, or less t!an an integer, depending upon t!e implementation.

    e.g.

    s!ort int i/

    Some implementations !ave t!e @ualifier signed. Fll t!evariables by default are signed, t!erefore t!is @ualifier is not of muc!use.

    1.. aria-les

    )nformation stored in a variable can c!ange in t!e course of t!eprogram. #!e type used in t!e definition describes t!e $ind ofinformation t!e symbol can store. Variables are addressable.

    1.1. /ules for naming the 0aria-les'

    Can !ave c!aracters, digits and underscore.

    Can start it! c!aracter or underscore.

    Fre case sensitive i.e., fan is different from :an and :FK.

    CanAt use $eyords

    Ko limits on t!e lengt! of t!e ord.

    e.g.

    int poodle ++ Validint myLstud ++ Validint Lmystud ++ Valid

    124

  • 8/14/2019 OOP- Notes.doc

    6/190

    int 8ever ++ )nvalid starts it! numberint double ++ )nvalid $eyordint not alloed as it

    ++ is a special c!aracter.

    Variables !elp us to reuse t!e codes. #o find t!e value of poerof some number e may rite,

    e.g.

    #o find t!e value of poer of some number e may rite,

    cout NN 3O3O3O3O3O3O3O3O3O3 for 3P7. +O cout is e@uivalentto printf=> in C. )t prints

    t!e literals or values of variables.O+

    )f e ant to find t!e poer of some number or if e ant toc!ange t!e number e !ave to type t!e !ole sentence again. e cangenerali0e t!is operation by using 3 variables as follos.

    e.g.

    int val 8, po , cnt / for = cnt / cnt N po/ %%cnt >

    res resOval/

    #!is is flexible compared to previous met!od but not reusable. Byusing functions e can ma$e t!em reusable too.

    e.g.

    int po= int val , int exp >

    for = res / exp / --exp >

    res res O val/ return res/

    Tou can call t!is function any number of times it! differentarguments. aria-les can alternati0el -e called as -ects.

    125

  • 8/14/2019 OOP- Notes.doc

    7/190

    There are two terms associated with a variable :

    . r-value = read value> * ;ata. #!is can be a literal

    or variable name.3. l-value =location value> * Fddress in t!e memorylocation !ere data is stored.

    e.g.

    c! c! - A/

    !ere c! is l-value,c! is r-value symbol,A is r-value literal.

    Tou can !ave t!e same symbol in bot! l-value and r-value.

    e.g.

    c! c! - A/

    / ++ ?rror, cannot !ave a literal as l-value.

    salary % extra nesal ++ ?rror, l value must be an++ addressable variable and not an expression.

    'b(ects or variables can !ave only a single location. So, t!ey

    canAt be defined tice.

  • 8/14/2019 OOP- Notes.doc

    8/190

    '

    #!e $eyord etern informs t!e compiler t!at t!e filename isdefined some!ere outside t!e existing file. )f you need to declare

    many variables in different files you can declare once in a !eader fileand include it in files !ere t!e declarations are needed.

    1.11. 4he definition of an o-ect(0aria-le )'

    e can define a variable=set memory to t!e variable> in t!efolloing ays.

    e.g.

    double salary/int mont!/

    !en more t!an one variable of same type are needed a commacan be used to declare multiple variables.

    e.g.

    double sal , age/ int m , d , y , $ , a / ++ Can span multiline too.

    )f t!e variables are declared globally, t!ey are initiali0ed to 0eroby default constructors= functions t!at are used to initiali0e t!evariables> t!at are inbuilt . )f t!ey are declared locally e !ave toinitiali0e t!em as t!ey may !ave some (un$ value stored in t!em.

    e.g.

    int x/ ++ Ulobal , initiali0ed to 0ero.

    void main=>

    int i/ ++ "ocal , not initiali0ed/

    You can initialize the variables in the following ways.

    e.g.

    127

  • 8/14/2019 OOP- Notes.doc

    9/190

    int ival /int ival=>/

    double sal ., age sal % /

    int mon 1, day 9, year 964/

    )n C%%, special constructors are inbuilt t!at support initiali0ation.

    e.g.

    int ival int=>/ ++ Sets ival / double dval double=> / ++ Sets dval to ./

    Fn ob(ect can be initiali0ed it! an arbitrary complex expression.

    e.g.

    double pr 99.99. disc .1/ double sale= pr O disc >/

    1.12. /ecursi0e Functions

    Recursion is a process by !ic! a function invo$es itself it! acondition for its safe exit. )t is best suitable for a recursive problem. Ftypical example is t!e factorial problem, t!e programs it!out andit! recursive functions are s!on belo.

    void main=> long factorial = int num>/ ++ :orard declaration of

    ++a function int num/ printf=HDn ?nter a number*E>/

    scanf=H4dE,num>/printf=H :actorial of 4d is WldE,num,factorial=num>>/

    long factorial=int num> ++ Kon recursive long f/

    128

  • 8/14/2019 OOP- Notes.doc

    10/190

    !ile = n> f f O n/

    n--/return=f>/

    long factorial=int num> ++ Recursive if=n >

    return =>/ else

    return= nO factorial=n->>/

    1.13. Sco$e /ules and Storage Classes

    #!e storage class determines t!e life of a variable in terms of itsduration or its scope. #!ere are four storage classes *

    automaticstaticexternal

    register

    1.13.1 5utomatic aria-les

    Futomatic variables are variable !ic! are defined it!in t!efunctions. #!ey lose t!eir value !en t!e function terminates. )t can beaccessed only in t!at function. Fll variables !en declared it!in t!efunction are , by default, are automatic.

  • 8/14/2019 OOP- Notes.doc

    11/190

    cout NNHDnENN H Value of i after incrementing is *NNi/

    void main=>

    print=>/print=>/print=>/

    'utput*Value of i before incrementing is * Value of i after incrementing is * Value of i before incrementing is * Value of i after incrementing is *

    Value of i before incrementing is * Value of i after incrementing is *

    1.13.2. Static aria-les

    Static variables !ave t!e same scope s automatic variables, but ,unli$e automatic variables, static variables retain t!eir values overnumber of function calls. #!e life of a static variable starts, !en t!efirst time t!e function in !ic! it is declared, is executed and itremains in existence, till t!e program terminates. #!ey are declared

    it! t!e $eyord static.

    e.g.

    void print=> static int i /

    cout NN H Value of i before incrementing is *NN i/i i % /cout NNEDnENN H Value of i after incrementing is *NNi/

    void main=>

    print=>/print=>/print=>/

    130

  • 8/14/2019 OOP- Notes.doc

    12/190

    'utput*

    Value of i before incrementing is * Value of i after incrementing is * Value of i before incrementing is * Value of i after incrementing is * 3Value of i before incrementing is * 3Value of i after incrementing is * 5

    )t can be seen from t!e above example t!at t!e value of t!evariable is retained !en t!e function is called again. )t is allocatedmemory and is initiali0ed only for t!e first time.

    1.13.3. %6ternal aria-les

    ;ifferent functions of t!e same program can be ritten indifferent source files and can be compiled toget!er. #!e scope of aglobal variable is not limited to any one function , but is extended to allt!e functions t!at are defined after it is declared.

  • 8/14/2019 OOP- Notes.doc

    13/190

    ++ :)"? 3 )f t!e variable declared in file is re@uired to be used infile 3 t!en it is to be declared as an extern.

    extern int g /

    void fn3=>

    **

    void fn5=>

    *

    1.13.. /egister aria-le

    Computers !ave internal registers, !ic! are used to store datatemporarily, before any operation can be performed. )ntermediateresults of t!e calculations are also stored in registers. 'perations canbe performed on t!e data stored in registers more @uic$ly t!an on t!edata stored in memory. #!is is because t!e registers are a part of t!e

    processor itself. )f a particular variable is used often for instance, t!econtrol variable in a loop, can be assigned a register, rat!er t!an avariable . #!is is done using t!e $eyord register. register int i/

    for=i/ iN / i%%>

    cout NN i/

    132

  • 8/14/2019 OOP- Notes.doc

    14/190

  • 8/14/2019 OOP- Notes.doc

    15/190

    y -x/a 0/

    #!e value of y no becomes 4 and XaX becomes -.

    . #!ey can be used as prefix or postfix to t!evariable, and t!eir meaning c!anges depending on t!eir usage. !enused as prefix, t!e value of t!e variable is incremented+ decrementedbefore using t!e expression. But !en used as postfix, its value is first

    used and t!en t!e value is incremented or decremented.

    e.g.

    --x/x--/

    )n t!e above example it does not matter !et!er t!e decrementoperator is prefixed or suffixed. )t ill produce t!e same result.

  • 8/14/2019 OOP- Notes.doc

    16/190

    %A for addition.- for subtraction.OA fro multiplication.+A for division .

    WA for modulus.

    e.g.

    0 x % y/f + 5/f W s/x a % b c + d O e/x ==a % =b c> + d >O e/

    #!e second example ill give t!e @uotient of divided by 5,

    !ere as t!e t!ird example ill give t!e remainder after division.

    #!e expressions in t!e fourt! example is evaluated according tot!e precedence of operators, !ic! is as follos*

    W, +, O on t!e same level, evaluated from left to rig!t.%, - on t!e same level, evaluated from left to rig!t.

    Frit!metic expressions can also contain parent!esis to overridet!e precedence, as s!on in t!e last example.

    1.1.3. Com$ound 5ssignment $erators

    Fpart from t!e binary and t!e unary arit!metic operators, ealso !ave compound assignment operators. #!ese are %, -, O, +,W. 2sing t!ese operators, t!e expression

    x x % 4/

    can also be ritten as

    x % 4/

    #!is !elps in riting compact code.

    1.1.. /elational $erators

    F relational operator is used to ma$e comparison beteen tovalues. Fll t!ese operators are binary and re@uire to operands. #!ereare t!e folloing relational operators *

    135

  • 8/14/2019 OOP- Notes.doc

    17/190

    e@ual toZ not e@ual to greater t!an

    greater t!an or e@ual toN less t!anN less t!an or e@ual to

    e.g.

    number N 1c! Z aAtotal

    Kote t!at no space is given beteen t!e symbols. Fll t!ese

    operators !ave e@ual precedence amongst t!emselves and a loerprecedence t!an t!e arit!metic operators.

    1.1.". Logical $erators

    e say any expression t!at evaluates to 0ero is a :F"S? logiccondition and t!at evaluating to non-0ero value is a #R2? condition."ogical operators are useful in combining one or more conditions. #!efolloing are t!e logical operators *

    FK;[[ 'RZ K'#

    #!e first to operators are binary, !ereas t!e exclamation=Z> isa unary operator. )t is used to negate t!e condition.

    e.g.xN y evaluates to true if bot! conditions are

    truex N [[ 0 evaluates to true, if one of t!e

    conditions is true

    Z=x > evaluates to true if condition isfalse.

    #!e unary negation operator=Z> !as a !ig!er precedenceamongst t!e t!ese, folloed by t!e and => operator and t!en t!eor=[[> operator, and are evaluated from left to rig!t.

    136

  • 8/14/2019 OOP- Notes.doc

    18/190

    1.1.#. !it;

  • 8/14/2019 OOP- Notes.doc

    19/190

    B)# B)#3 B)# B)# B)# [ B)#3 B)# P B)#3

    e.g.

    c!ar x, y, 0, a, b/

    a x/ +O O+b x4/ +O O+

    x a b/y a P b/0 a [ b/x y/y [ 0/

    #!e result of x is x, since

    a b

    x

    1.1.. 4he Shift $erators

    #!ere are to s!ift operators * left s!ift = NN> and rig!t s!ift

    =>. #!ese are binary operators. #!e format isoperand number or operand NN number

    #!e first operand is t!e value, !ic! is to be s!ifted. #!e secondis t!e number of bits by !ic! it is s!ifted. #!e left s!ift operators s!iftnumberA bits to t!e left, !ereas t!e rig!t s!ift operators s!iftnumberA bits to t!e rig!t. #!e leftmost and t!e rig!tmost bits ares!ifted out and are lost.

    138

  • 8/14/2019 OOP- Notes.doc

    20/190

    e.g.c!ar x, y x7/

    y y 5/x y NN3/y NN /x 3/

    #!e c!ar y= !ic! is allocated a byte of space on a 1-bitmac!ine> ill !ave its bits s!ifted to t!e rig!t t!ree places. #!e valueof y !ic! as x7= > is c!anged to x:o= > , aftery y5.

    1.1.. Precedence and rder of e0aluation

    #!e languages follo a standard precedence for basic operators.&recedence rules !elp in removing ambiguity of t!e order of operationsperformed !ile evaluating an expressions. Flso important for t!ispurpose is t!e associativity of t!e operators, associativity defines t!edirection in !ic! t!e expression is evaluated !en t!e operator isinvolved. #!e precedence and associativity of t!e operators issummari0ed belo*

    $erator 5ssociati0it

    => IJ - left to rig!t

    Z \ %% -- =type>O si0eof rig!t to left

    O + W left to rig!t

    % - left to rig!t

    NN left to rig!t

    Z left to rig!t

    left to rig!t

    139

  • 8/14/2019 OOP- Notes.doc

    21/190

    P left to rig!t

    [ left to rig!t

    left to rig!t

    [[ left to rig!t

    ] * rig!t to left

    % - etc. rig!t to left

    , left to rig!t

    'perators on t!e same line !ave t!e same precedence/ ros arein order of decreasing precedence, so, for example, O, +, W all !ave t!esame precedence !ic! are !ig!er t!an t!at of % and on t!e nextline.

    1.1.. 4he si?eof() o$erator

    #!is is a pseudo-operator given by t!e language, !ic! returnst!e number of bytes ta$en up by a variable or data type. #!e valuereturned by t!is operator can be used to determine t!e si0e of a

    variable.

    si0eof=int>/ ++ returns 3 on a 1bit mac!inesi0eof=float>/ ++ returns 8 on a 1bit mac!ine

    1.1". 8i6ed 8ode %6$ressions and Im$licit t$e Con0ersions

    F mixed mode expression is one in !ic! t!e operands are not oft!e same type. )n t!is case, t!e operands are converted beforeevaluation, to maintain compatibility of t!e data types. #!e folloing

    table s!os t!e conversion *

    $erand1 o$erand 3 /esult

    c!ar int int

    140

  • 8/14/2019 OOP- Notes.doc

    22/190

    int long long

    int double double

    int float float

    int unsigned unsigned

    long double double

    double float double

    e.g.

    c!ar c! FA/

    c! c! % 53/

    in t!e expression. #!e result ill be an integer.

    e.g.

    float f ./int i /

    i f + 5/

    )n t!is expression , t!e constant 5 ill be converted to a float andt!en floating point division ill ta$e place, resulting in 5.55555, butsince t!e lvalue is an integer t!e value ill be automatically truncatedto 5 and t!e fraction part is lost. = implicit conversion from float to int >.

    1.1#. 4$e Casting

    )mplicit type conversions, as alloed by t!e language, can lead

    to errors creeping in t!e program if care is not ta$en. #!erefore,explicit type conversions may be used in mixed mode expressions.#!is is done by type-casting a value of a particular type, into t!edesired type. #!is is done by using t!e =type> operator as follos*

    =type> expression

    expression is converted to t!e given type by t!e rules stated above.

    141

  • 8/14/2019 OOP- Notes.doc

    23/190

    e.g.

    float a ., b 5., c/

    c a + b/

    #!is expression ill result in 5.555555 being stored in cA. )f t!eapplication re@uires integer division of to floating point numbers,t!en t!e folloing expression it! t!e type cast can be used*

    c =int>a + =int>b/or

    c =int> =a + b>/

    1.1. Control Flo

    statements/ else

    statements/

    142

  • 8/14/2019 OOP- Notes.doc

    24/190

    )f t!e expression is evaluated to be true t!e statements under it areexecuted ot!erise if it is rong t!e statements ritten after t!e$eyord elseare executed.

    e.g.

    if= c! N A [[ c! 9A>

    cout NN H Kot a Kumber>/ else ++ in case of a single statement t!e

    braces can be avoided. coutNNE #!is is a numberE/

    F single if=expression> it!out an else can also be used forc!ec$ing a single condition.

    F multi-ay decision ma$ing segment can be ritten by using ifstatements inside t!e else part, !ic! gives t!e else-if construct.

    e.g.

    if= option >coutNNE E/

    else if= option 3>

    coutNNE 33333E/else if= option 5>

    coutNNE 55555E/else

    cout NN H invalid H/

    #!ey can be nested as ell*

    e.g.

    if=expression >

    if = expression 3>

    **

    else

    143

  • 8/14/2019 OOP- Notes.doc

    25/190

    else

    if = expression 3>

    **

    else

    1.1.1.2. 4he Conditional %6$ression $erator

    Fn alternate met!od to using a simple if-else construct is t!econditional expressions operator, ]*

    F conditional expression operator is a ternary operator, it !ast!ree operand, !ose general format is*

    expression ] expression3 * expression5

    0 a/else 0 b/

    #!is can be ritten as

    144

  • 8/14/2019 OOP- Notes.doc

    26/190

    0 =ab> ] a* b/

    1.1.1.3. 4he S

    case value * statements/**

    brea$/

    case value3 * statements/**

    brea$/

    case value5 * statements/

    **

    brea$/

    default * statements/**

    #!e expression must be declared in t!e parent!eses, and t!ebody of t!e sitc! statement must be enclosed in braces. #!e values

    it! case s!ould be constants. #!e expression is evaluated andcompared it! t!e values in cases, if it matc!es t!e statements underit are executed till it encounters a brea$ statement. )f t!e value doesnot matc! it! any of t!e case statements t!en t!e statements undert!e default label are executed.

    'mission of brea$ ta$es control t!roug! t!e next casestatements regarded !et!er t!e value of case matc!es or not. #!is

    145

  • 8/14/2019 OOP- Notes.doc

    27/190

    can also be used constructively !en same operation !as to beperformed on a number of cases.

    e.g.

    sitc!=c!>

    case aA *case eA *case iA *case oA *case uA * cout NN HVoelE/default * cout NN H Consonant H/

    )n t!e above example if t!e value of c! is any of a,e,i,o,u t!ent!ey are printed as voels , ot!erise t!ey are printed as consonants.

    1.1.2 Loo$ing Statements

    #!e statements generally used for looping are for# do$while#while. #!e goto statement can be used for looping# but its use isgenerally avoided as it leads to hapha%ard code and also increases thechances of errors.

    1.1.2.1. 4he for Loo$

    #!is is a controlled form of loop. #!e general format is *

    for= initiali0e / test / update> statements/

    **

    #!e initiali0e part is executed only once, before entering t!eloop. )f test evaluates to false t!en t!e next statement after for loop isexecuted. )f t!e test evaluates to true t!en t!e updating ta$es place.

    e.g.

    146

  • 8/14/2019 OOP- Notes.doc

    28/190

    for= int i / iN / i%%> ++ )n C%% you can declare avariable !ere.

    cout NN i/

    #!is ill print from to .

    #!e expressions in t!e for loop are optional but t!e semi-colonsare necessary, i.e.,

    for= / / >

    coutNNE!elloE/

    #!is is an infinite loop, it! no expression.

    e.g.int i

    for=/ iN / >

    cout NN i/i%%/

    #!is is e@uivalent to our example, !ic! printed from to 9.^ore t!an one expression can also be inside t!e for loop by separatingt!em using commas.

    e.g.

    for= int i , int (/ iN y / i%%, y-->

    cout NN i/

    1.1.2.2. 4he

  • 8/14/2019 OOP- Notes.doc

    29/190

    !ile=condition>

    statements/*

    #!e statements in t!e loop are executed as long as t!e conditionis true .

    e.g.

    int x /

    !ile= x N >

    cout NN x/

    #!is example prints from to .

    1.1.2.3. 4he do../

    e.g.

    do

    cout NN x/

    !ile= x N >/

    #!is or$s exactly li$e our previous example . t!e do.. !ile loopis exactly li$e !ile loop, it! one difference.

  • 8/14/2019 OOP- Notes.doc

    30/190

    after t!e expression is c!ec$ed e enter t!e loop. e can say do loopis executed at least once.

    1.1.3. 4he -rea@ statement

    #!e brea$ statement, !ic! as already covered in t!e sitc!..case , can also be used in t!e loops. !en a loop statement isencountered in t!e loops t!e control is transferred to t!e statementoutside t!e loop. !en t!ere are nested loops it brea$s only from t!ecurrent loop in !ic! it as ritten.

    1.1.. 4he continue statement

    #!e continue statement causes t!e next iteration of t!eenclosing loop to begin. !en t!is is encountered in t!e loop , t!e restof t!e statements in t!e loop are s$ipped and control passes to t!econdition.

    "et us see an example t!at accepts a variable amount of numbersfrom t!e $eyboard and prints t!e sum of only positive numbers.

    e.g.

    void main=>

    int num, total /

    do

    cout NN H enter to @uit H/cin num/ ++ e@uivalent to scanf=>

    if=num >brea$/

    if=num N >continue/

    total%num/!ile=>/

    cout NN total/

    149

  • 8/14/2019 OOP- Notes.doc

    31/190

    1.1.". 4he goto statement

    #!is statement can be used to branc! to anot!er statement oft!e program. #!is is rarely used as it violates t!e principle ofstructured programming. folloed by a colon.

    e.g.

    for= . . . >

    for= . . . >

    for= . . . >

    for= . . . >

    if= condition>

    goto cleanup/

    cleanup* statements/**

    F good programmer ill use control statements effectively in

    order to avoid t!e usage of unconditional branc!ing statement goto.

    #!is session introduced some features of t!e C and C%%languages. #!e data types offered, @ualifiers to t!e data types, t!escope rules and storage met!ods ere also discussed in t!is session.#!e control flo re@uired for any language to be structured as also

    150

  • 8/14/2019 OOP- Notes.doc

    32/190

  • 8/14/2019 OOP- Notes.doc

    33/190

    element arrIJFn array definition consists of a type specifier, an identifier ,and

    a dimension.

    ;imension specifies t!e number of elements contained in t!earray. Fn array must be given dimension si0e greater t!an or e@ual to. #!e dimension value must be a constant expression. i.e., t!e values!ould be available at compile time.

    e.g.

    extern int getsi0e=>/const int a , b 3/int c 5/

    c!ar cLarrIaJ/ ++ validint iLarrIb-5J/ ++ valid ,constant expression.

    ?valuates to 6 during compilation.int iLarrIcJ/ ++ ?RR'R* non-constant variable. #!oug! it is

    initiali0ed, access to its value can only beaccomplis!ed runtime.

    int iLarrIgetLsi0e=>J/ ++ ?RR'R* non-constant expression

    #!e elements of an array are numbered beginning it! . :or anarray of elements , t!e index values are t!roug! 9.

    2.2. arious

    const int si0e /int arrIsi0eJ/

    for=int i / i N si0e / i%% > ++ Tou can declare avariable !ere in C%%.

    arrIiJ i/

    Fn array can be eplicitlyinitiali0ed as follos.

    152

  • 8/14/2019 OOP- Notes.doc

    34/190

    e.g.int arrI5J ,,3/

    Fn explicitly initiali0ed array need not specify si0e but if specifiedt!e number of elements provided must not exceed t!e si0e. )ft!e si0e is given and some elements are not explicitly initiali0edt!ey are set to 0ero

    e.g.

    int arrIJ ,,3/

    int arrI4J ,,3/ ++ )nitiali0ed as ,,3,,

    const c!ar aLarrIJ cA.A%A,A%A ++si0e 5/

    const c!ar aLarr3IJ Hc%%E ++si0e 8 because ofnull c!aracter at t!e

    end of t!e string/

    const c!ar aLarr5I1J E;anielE/ ++ ?RR'R/ ;aniel !as 6elements

    Fn array cannot be initiali0ed it! or assigned to anot!er array.

    e cannot !ave array of references.

    e.g.

    int ix,iy,i0/

    int OarrIJ ix,iy,i0/ ++Can !ave array of pointers

    int arrIJ ix,iy,i0/ ++ ?RR'R* cannot !ave arrayof references.

    int arr3IJ ,3,5/ ++ valid

    int arrIJ arr3/ ++ ?RR'R* canAt initiali0e onearray to ant!er

    arr arr3/ ++ ?RR'R* canAt assign one arrayto anot!er.

    153

  • 8/14/2019 OOP- Notes.doc

    35/190

    #o copy one array to anot!er eac! element !as to be copiedusing for structure.

    Fny expression t!at evaluates into an integral value can be used

    as an index into array.

    e.g.

    arrIgetLvalue=>J somevalue/

    2.3. 8ultidimensional 5rras

    ?ac! dimension is specified in separate brac$ets

    e.g.

    int arrI8JI5J/

    #!is is a to-dimensional array it! 8 as ro dimension and 5 asa column dimension.

    ^ultidimensional array can be initiali0ed as follos

    e.g.

    int arrI8JI5J ,,3,5,8,4,1,6,7,9,,/

    #!e nested brac$ets are optional.

    e.g.

    int arrI8JI5J ,,3,5,8,4,1,6,7,9,,/

    int arrI8JI5J ,,3,5/ ++ :irst element ofros are ,,3,5

    and remaining areconsidered 0ero.

    int arrI8JI5J ,3,5/ ++ )nitiali0es first t!reeelement of first ro as

    ,3,5, and remaining ele-ments are considered Gero.

    )nitiali0ation using nested loops.

    154

  • 8/14/2019 OOP- Notes.doc

    36/190

    e.g.

    int arrIJIJ/

    for=int i /iN /i%%> for=int ( / (N /(%%>

    arrIiJI(J i%(/

    )nstead of arrIJI3J if you give arrI,3J is considered as arrI3J.

    2..Pointer 4$es

    &ointer !olds t!e address of an ob(ect, alloing fort!e indirect manipulation of t!at ob(ect. #!ey are used increating lin$ed data structures li$e lists, trees and managementof ob(ects t!at are dynamically created during programexecution.

    &ointers are declared using t!e =O> operator. #!egeneral format is*

    type Optrname/

    type can be of any data type and pointer name becomest!e pointer of t!at data type.

    e.g.

    int Oiptr/ c!ar Ocptr/

    float Ofptr/

    #!e pointer iptr stores t!e address of an integer. )n ot!er

    ords it points to an integer, cptr to a c!aracter and fptr to afloat value.

    'nce t!e pointer variable is declared it can be made topoint to a variable it! t!e !elp of a address=reference>operator=>.

    155

  • 8/14/2019 OOP- Notes.doc

    37/190

    e.g.

    int num 38/ int Oiptr/

    iptr num/ ++ iptr points to t!e variable num.

    )n t!e folloing example lptr is a pointer to long variableand lptr3 is a normal long variable.

    e.g.

    long Olptr, lptr3/

    Tou can declare a pointer variable in to ays.

  • 8/14/2019 OOP- Notes.doc

    38/190

    e.g.

    double dval, Odptr dval/ ++ alloed iptr dval / ++not alloed

  • 8/14/2019 OOP- Notes.doc

    39/190

    int OOptriptr iptr/

    e dereference it as follos.

    int Oiptr5 Optriptr/ ++ content is an address.

    2.". Pointer 5rithmetic

    e can manipulate t!e pointers too. e can perform operationsli$e addition, subtraction, increment and decrement etc.,. Since t!epointer variables contain address, adding or subtracting a numberresults in anot!er address, !ic! is at an offset from t!e original

    address. #!is may be memory address occupied by anot!er variable.

    e.g.

    int i, (, $ /

    int Oiptr i/

    Oiptr Oiptr % 3/ ++ ) ) % 3/

    iptr iptr % 3 ++ adds 3 to address.

    #!ese are useful !en using arrays.

    e.g.

    int arrIJ/

    int Oiptrb arrIJ/

    int Oiptre arrIJ/

    !ile = iptrb Z iptre>

    ;o somet!ing it! t!e value if =Oiptrb>/

    %%iptrb/

    158

  • 8/14/2019 OOP- Notes.doc

    40/190

    2.#. /elationshi$ -et

    !ile=arrLbeg Z arrLend>

    cout NN arrLbeg/%%arrLbeg/

    void main=>

    int arrIJ ,,3,5,8,4,1,6,7,9 print=arr,arr%9>/

    159

  • 8/14/2019 OOP- Notes.doc

    41/190

    arrLend initiali0es element past t!e end of t!e array so t!at ecan iterate t!roug! all t!e elements of t!e array. #!is !oever or$sonly it! pointers to array containing integers.

    2.. Structures

    F structure is a derived data type. )t is a combination of logicallyrelated data items. 2nli$e arrays, !ic! are a collection of li$e datatypes, structures can be made of members of unli$e data type. #!edata items in t!e structures generally belong to t!e same entity , li$einformation of an employee, players etc.

    #!e general format of structure declaration is*

    struct tag

    type member/type member3/type member5/**

    variables/

    e can omit t!e variable declaration in t!e structure declarationand define it separately as follos *

    struct tag variable/

    )n C%% e can omit struct and simply rite *

    tag variable/e.g.

    Structure definition.

    struct account

    int accnum/c!ar acctype/c!ar nameI34J/float balance/

    /

    160

  • 8/14/2019 OOP- Notes.doc

    42/190

    Structure declaration.

    struct account oldcust/ IorJ

    account necust/

    e can refer to t!e member variables of t!e structures by usinga dot operator =.>.

    e.g.

    necust.balance .

    cout NN oldcust.name/

    e can initiali0e t!e members as follos *

    e.g.

    account customer , A, ;avidA, 14./

    e cannot copy one structure variable into anot!er. )f t!is !as tobe done t!en e !ave to do memberise assignment.

    e can also !ave nested structures as s!on in t!e folloingexample *

    struct date

    int dd, mm, yy//

    struct account

    int accnum/c!ar acctype/c!ar nameI34J/

    float balance/struct date d/

    /

    Ko if e !ave to access t!e members of date t!en e !ave touse t!e folloing met!od.

    account c/

    161

  • 8/14/2019 OOP- Notes.doc

    43/190

    c.d.dd3/

    e can pass and return structures into functions . #!e !ole

    structure ill get copies into formal variable .

    e can also !ave array of structures. )f e declare array toaccount structure it ill loo$ li$e,

    account aIJ/

    ?very t!ing is same as t!at of a single element except t!at itre@uires subscript in order to $no !ic! structure e are referring to.

    e can also declare pointers to structures and to access member

    variables e !ave to use t!e pointer operator - instead of a dotoperator.

    account Oaptr/

    cout NN aptr-name/

    F structure can contain pointer itself as one of t!e variables ,alsocalled self-referential structures.

    e.g.

    struct info

    int i,(,$/

    info Onext//

    2..%numerated Constants

    ?numerated constants enable t!e creation of ne types and t!en

    define variables of t!ese types so t!at t!eir values are restricted to aset of possible values.

    e.g.

    enum ColourR?;, B"2?, UR??K,

  • 8/14/2019 OOP- Notes.doc

    44/190

    Colour is t!e name of an enumerated data type. )t ma$es R?; asymbolic constant it! t!e value , B"2? a symbolic constant it! t!evalue and so on.

    ?very enumerated constant !as an integer value. )f t!e programdoesnAt specify ot!erise, t!e first constant ill !ave t!e value, t!e remaining constants ill count up by as compared tot!eir predecessors.

    Fny of t!e enumerated constant can be initialised to !ave aparticular value, !oever, t!ose t!at are not initialised ill countupards from t!e value of previous variables.

    e.g.

    enum ColourR?; , B"2?, UR??K 4,

  • 8/14/2019 OOP- Notes.doc

    45/190

    #!ere is no support for moving bac$ard or forard from oneenumerator to anot!er.

  • 8/14/2019 OOP- Notes.doc

    46/190

  • 8/14/2019 OOP- Notes.doc

    47/190

    const double dr dval %./

    #!e same initiali0ations are not legal for non-constantreferences.

    )nternally, a reference maintains t!e address of t!e ob(ect for!ic! it is an alias. )n case of non-addressable values, suc! as literalconstant and ob(ects of different types, t!e compiler generates atemporary ob(ect t!at reference actually addresses but user !as noaccess to t!ese addresses.

    e.g.

    double dval 38/const int ri dval/

    #!e compiler transforms t!is as,

    int temp dval/const int ri temp/

    Ko if e try to c!ange ri, it actually c!anges temp and not dval as itis a constant

    e can initialise a reference to t!e address of a constant ob(ect.)f e rite,

    const int ival /int OpiLref ival/ ++ e re@uire constant reference.

    )f e rite,

    const int OpiLref ival/

    +O t!is is reference to a pointer to an ob(ect of type int defined tobe a constant. 'ur reference is not to a constant but rat!er to a non-constant, !ic! addresses a constant ob(ect.O+

    #!e correct form is,

    int Oconst piLref ival ++o.$.

    2.1. :ifferences -et

  • 8/14/2019 OOP- Notes.doc

    48/190

    . F reference must alays point to some ob(ect !ere as t!isrestriction is not imposed on a pointer.

    e.g.

    int Opi / ++ pointer can point to no ob(ect.

    const int ri ould be converted as ,int temp /const int ri temp/

    3. #!e assignment of one reference it! anot!er c!anges t!e ob(ectbeing referenced and not t!e reference itself.

    e.g.

    int ival , ival3 3/int Opi ival, Opi3 ival3/int ri ival, ri3 ival3/

    pi pi3/

    ival remains unc!anged but pi and pi3 no address t!e sameob(ect ival3.

    ri ri3/

    ival becomes 3. ri and ri3 still refer to ival and ival3respectively.

    2.11. 7nions

    F union is also li$e a structure , except t!at only one variable int!e union is stored in t!e allocated memory at a time. )t is a collection

    of mutually exclusive variables , !ic! means all of its membervariables s!are t!e same p!ysical storage and only one variable isdefined at a time. #!e si0e of t!e union is e@ual to t!e largest membervariables. F union is defined as follos *

    union tag

    type memvar/

    167

  • 8/14/2019 OOP- Notes.doc

    49/190

    type memvar3/type memvar5/**

    /F union variable of t!is data type can be declared as follos,

    2nion tag variableLname/

    e.g.

    union utag

    int num/c!ar c!//

    union tag filed/

    #!e above union ill !ave to bytes of storage allocated to it.#!e variable num can be accessed as field.sum and c! is accessed asfield.c!. Ft any time, only one of t!ese to variables, can be referredto. Fny c!ange made to one variable affects anot!er.

    #!us unions use memory efficiently by using t!e same memoryto store all t!e variables, !ic! may be of different types, !ic! existat mutually exclusive times and are to be used in t!e program onlyonce.

    #!is session covered advanced concepts of t!e language li$epointers, arrays, references, and relation beteen t!em . Fs can beseen pointers and references can be used to return more t!an onevalue from t!e functions, to speed t!e processing and to use memorymore efficiently. #!e session also covered t!e concepts of structures

    and unions. #!e structures or records are t!e basic elements of adatabase. !en t!ey are used it! pointers, arrays etc, complexdatabase management can be reali0ed. #!e unions are used to storevariables of different types t!at are re@uired atmutually exclusive times.

    168

  • 8/14/2019 OOP- Notes.doc

    50/190

    %6ercises

    . rite a &rogram=F&> to print a given integer in t!e reverseorder. i.e. 3584 is printed as 4853

    3. F& a program to print first K prime numbers !ere K isaccepted from t!e user.5. F& to print t!e sum of s@uares beteen K, !ere K is

    accepted from t!e user.8. F& to convert a decimal number into its e@uivalent of any

    ot!er base=3,7,1>.4. F& to accept an array of c!aracter strings and print t!em in

    descending order.

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

    Session 3

    -ect riented Programming ' 5n Introduction

    During this session you will learn about :

    &rocedural, Structural and 'b(ect-'riented &rogramming logic.

    ;ifferent implementation of ''&.

    )ntroduction to C%%.

    C%% and ''&.

    ;ifferences beteen C and C%%.- Fdditional $eyords in C%%.- Comments .- Variable declarations.

    ;efault arguments.

    #!e ne and delete operators.

    #!e cin and cout ob(ects.

    )n earlier sessions e learnt about language features !ic! !ad

    not!ing to do it! 'b(ect 'riented &rogramming tec!ni@ues. #!issession introduces t!e features of 'b(ect 'riented programming andalso discusses ot!er programming met!ods. e can also see featuresof C%% t!at are not present in C.

    169

  • 8/14/2019 OOP- Notes.doc

    51/190

    3.1 Procedural, Structured, and -ect;riented Programminglogic

    2ntil recently, programs ere envisioned as a series ofprocedures t!at acted on data. Fprocedure#or function, as definedas a set of specific instructions executed in se@uential manner. #!edata is $ept separate from t!e procedures, and t!e tric$ inprogramming as to $eep trac$ of, !ic! functions called !ic!functions, and !ic! data as c!anged. #o ma$e sense of t!ispotentially confusing situation, structured programming as created.&ascal is a language, !ic! uses procedural met!od of programming.

    #!e principal idea be!ind structured programmingas as simpleas t!e idea of Hdivide and [email protected] F computer program could be

    regarded as consisting of a set of tas$s. Fny tas$ t!at as too complexto be simply described ould be bro$en into a set of smallercomponent tas$s, until t!e tas$s ere sufficiently small and self-contained to be easily understood. #!e language C uses structuredprogramming approac!.

    Structured programming remains an enormously successfulapproac! for dealing it! complex problems. By t!e late 97As,!oever, some of its deficiencies !ad become all too clear.

    :irst, t!e separation of data from t!e tas$s t!at manipulate t!e

    data became increasingly difficult to compre!end and maintain. )t isnatural to t!in$ of data =employee records, for example> and ays t!atdata can be manipulated =sort, edit, and so on> as related ideas.

    Second, programmers found t!emselves constantly reinventingne solutions to old programs. Reinventing in a ay is opposite ofreusability. &eusabilityinvolves building components t!at !ave $nonproperties, and t!en plugging t!ose components into a program, ast!e programmer needs t!em. #!is softare concept is modeled aftert!e !ardare orld/ !en an engineer needs a ne transistor, s!edoesnAt usually invent one but goes to big bin of transistors and finds

    one t!at fits !er needs, or per!aps modifies t!e found transistor. Kosimilar option existed for a softare engineer until reusability asdeveloped.

    'b(ect-oriented programming =''&> attempts to meet t!eseneeds, providing tec!ni@ues for managing enormous complexity,ac!ieving reuse of softare components, and coupling data it! t!etas$s t!at manipulate t!e data.

    170

  • 8/14/2019 OOP- Notes.doc

    52/190

    #!e essence of ob'ect$oriented programming is to treat data andt!e procedures t!at act on t!e data as a single Hob(ectE a self-contained entity it! an identity and certain c!aracteristics of its on.

    3.2 :ifferent im$lementations of P

    'b(ect-oriented programming is not particularly concerned it!t!e details of t!e program operation. )nstead, it deals it! t!e overalldesign of t!e program . #!e ''& features can be implemented in manylanguages t!at support t!em. C%% is one language t!at supports allt!e features of ''&. 't!er languages include Common "isp ob(ectsystem, Smalltal$, ?iffel, Fctor and t!e latest version of #urbo &ascal,_ava.

  • 8/14/2019 OOP- Notes.doc

    53/190

    3.. C++ and -ect;riented Programming

    C%% fully supports ob(ect-oriented programming, including t!e

    four pillars of ob(ect-oriented development * encapsulation# datahiding# inheritance# and polymorphism.

    Before discussing t!ese pillars let us $no about some ot!erterms associated it! ''&.

    #!e most important term is bstraction". Fbstraction meansignoring t!ose aspects of a sub(ect t!at are not relevant to t!e currentpurpose in order to concentrate more fully on t!ose t!at are relevant.#o an analyst !o is as good as a sub(ect expert it means c!oosingcertain t!ings or aspects of t!e system over ot!ers at a time. ^ost of

    t!e t!ings in t!e real orld are intrinsically complex, far more complext!an one can compre!end at a time. By using abstraction one selectsonly a part of t!e !ole complex instead or or$ing it! t!e !olet!ing. )t does not mean ignoring t!e details altoget!er but onlytemporarily, t!e details are embedded inside and are dealt it! at alater stage. Fbstraction is used by ''& as a primary met!od ofmanaging complexity.

    ssociation is t!e principle by !ic! ideas are connectedtoget!er or united. Fssociation is used to tie toget!er certain t!ingst!at !appen at some point in time or under similar conditions.

    ommunicating with messages is t!e principle for managingcomplexity, !ic! is used !en interfaces are involved tocommunicate beteen t!e entities. ''& uses classes and ob(ects !aveattributes, !ic! can be exclusively accessed by services of t!eob(ects. #o c!ange t!e attributes of t!e ob(ect =a data member of t!eob(ect>, a message !as to be sent to t!e ob(ect to invo$e t!e service.#!is mec!anism !elps in implementing encapsulation and dataabstraction.

    3..1. %nca$sulation and :ata Biding

    #!e property of being a self-contained unit is calledencapsulation. #!e idea t!at t!e encapsulated unit can be usedit!out $noing !o it or$s is called data !iding.

    ?ncapsulation is t!e principle by !ic! related contents of asystem are $ept toget!er. )t minimi0es traffic beteen different parts

    172

  • 8/14/2019 OOP- Notes.doc

    54/190

    of t!e or$ and it separates certain specific re@uirements from ot!erparts of specification, !ic! use t!ose re@uirements.

    #!e important advantage of using encapsulation is t!at it !elps

    minimi0e reor$ !en developing a ne system. #!e part of t!e or$,!ic! is prone to c!ange, can be encapsulated toget!er. #!us anyc!anges can be made it!out affecting t!e overall system and !encec!anges can be easily incorporated.

    Fs noted before, !en an engineer needs to add resistor to t!edevice s!e is creating, s!e doesnAt typically build a ne one from t!escratc!. S!e al$s over to a bin of resistors, examines t!e bin ofresistors, examines t!e colored bands t!at indicate t!e properties, andpic$s t!e one s!e needs. #!e resistor is a Hblac$ boxE as far as t!eengineer is concerned t!at is, s!e doesnAt care !o it does its or$

    as long as it conforms to !er specifications.

    Fll t!e resistorAs properties are encapsulated in t!e resistorob(ect t!ey are not spread out t!roug! t!e circuitry. )t is notnecessary to understand !o t!e resistor or$s to use it effectively,because its data is !idden inside t!e resistors casing.

    C%% supports t!e properties of encapsulation and data !idingt!roug! t!e creation of user-defined types, called classes. 'ncecreated, a ell-defined class acts as a fully encapsulated entity andcan be used as a !ole unit. #!e actual inner or$ings of t!e class

    s!ould be !idden/ users of ell-defined class do not need to $no !ot!e class or$s, only !o to use it.

    3..2. Inheritance and /euse

    Consider a car manufacturing company. !en t!ey ant to builda ne car, t!ey !ave to c!oices. #!ey can start from t!e scratc!, ort!ey can modify an existing model. &er!aps t!eir former model isnearly perfect =say CFR>, but t!ey ould li$e to add a turboc!argerand a six-speed transmission. #!e c!ief engineers ould prefer to use

    t!e earlier model and ma$e some c!anges to it t!an creating a neone =CFR3>.

    C%% supports t!e idea of reuse t!roug! inheritance. #!roug!t!is concept, a ne type can be declared t!at is an extension of t!eexisting type. #!is ne subclass is said to derive from t!e existing typeand is sometimes called a derived type.

    173

  • 8/14/2019 OOP- Notes.doc

    55/190

    3..3. Polmor$hism

    #!e CFR3 in t!e above example may respond differently t!an

    t!e CFR !en t!e car accelerates. #!e CFR3 mig!t engage fuelin(ection and a turboc!arger, for example, !ereas t!e CFR simplyget petrol into its carburetor. F user, !oever, does not !ave to $noabout t!ese differences/ t!e user simply presses t!e accelerator andt!e car responds it! t!e correct function.

    C%% supports t!is idea t!at different ob(ects do Ht!e rig!t t!ingH t!roug! function polymorp!ism and class polymorp!ism. *olymeans many, !ereas morphmeans form. #!us,polymorphism refersto t!e same name ta$ing many forms.

    3.". Some :ifferences !et andends it! t!e end of t!at line. F comment can start at t!e beginning oft!e line or on a line folloing t!e program statement. #!is form ofgiving comments is particularly useful for t!e s!ort line comments. )f acomment continues on more t!an a line, t!e to forard slas!ess!ould be given on every line.

    174

  • 8/14/2019 OOP- Notes.doc

    56/190

    #!e C style of giving a comment is also available in C%%. #!isstyle = +O`.O+> is particularly useful !en t!e comment spans moret!an a line.

    e.g.

    void main=>

    +O t!is is a good old style of giving a comment. )t can be continued to

    next line and !as to be ended it! O+

    clrscr=>/ ++ lears the +creeninit=>L/ ++ ,nitiali%e variables.

    **

    3.".3. aria-le :eclaration

    #!is declaration of variables in t!e C language is alloed only int!e beginning of t!eir bloc$, prior to executable program statements.)n C%% declaration of variables can be interspersed it! executableprogram statements. #!e scope id variables, !oever, remains t!e

    same t!e bloc$ in !ic! t!ey are declared.

    e.g.

    void main=> int x /

    printf =H t!e value of x W dDnE,x>/

    int y /

    for= int 0 / 0 N / / 0%%> ++ variable declared here.

    y %%/x %%/

    175

  • 8/14/2019 OOP- Notes.doc

    57/190

    Flt!oug!, a deviation from t!e old style of declaring all variablesin t!e beginning of t!e bloc$, t!is does save some amount of memory,

    i.e., a variable is not given a memory until t!e declaration statement.Flso, since a variable can be declared (ust before using it is suppose togive a better control over variables.

    3.".. 4he Sco$e /esolution $erator( '' )

    Ulobal variables are defined outside any functions and t!us canbe used by all t!e functions defined t!ereafter. to access t!e global variable t!us overriding alocal variable it! t!e same name. #!is operator is prefixed to t!ename of t!e global variable . #!e folloing example s!os its usage.

    int global /

    void main=>

    int global 3/

    printf=H _ust riting global prints * WdDnE, global>/

    printf=H riting **global prints * WdDnE, **global>/

    #!e output of t!is program ill be*

    _ust riting global prints * 3riting **global prints *

    3.".". :efault 5rguments

    F default argument is a value t!at is automatically assigned to aformal variable, if t!e actual argument from t!e function call isomitted.

    e.g.

    176

  • 8/14/2019 OOP- Notes.doc

    58/190

    void drabox= int x, int y, int x334, int y37,int color6>/ ++ *rototype

    void main = void >

    drabox=,,34,7,8>/ ++ parameters passeddrabox=>/ ++ uses default arguments

    void drabox= int x, int y, int x3, int y3,int color>

    ++ Body of the function

    :unction drabox=> dras a box around t!e edges of t!ecoordinates passed as parameters. )f t!ese parameters are omitted,t!en t!e default values, as given in t!e declaration are passed.

    !en a function is declared, default values must be added fromright to left.)n ot!er ords, a default value for a particular argumentcannot be given unless all default values for t!e arguments to its rig!tare given. #!is is @uite logical, since, if t!ere are some argumentsmissing in t!e middle t!en t!e compiler ould not $no as to !ic!arguments !ave been specified and !ic! s!ould be ta$en as default.

    e.g.

    void drabox= int x, int y, int x334, int y37,int color 6>/ ++ Valid

    void drabox= int x, int y, int x3, int y3,int color 6>/ ++Valid

    void drabox= int x, int y, int x334, int y37,int color >/ ++-ot Valid

    ;efault arguments are useful !en t!e arguments almost !avet!e same value. #!ey are also useful to increase t!e number ofarguments to a function in an already or$ing program. )n t!is case,using default arguments mean t!at existing function calls need not bemodified, !ereas, ne function calls pass more number ofarguments.

    177

  • 8/14/2019 OOP- Notes.doc

    59/190

    3.".#. 4he new and delete o$erators

    #!e C language !as defined library functions- malloc=> and free=>for dynamic allocation and de-allocation of memory. C%% provides yetanot!er approac! to allocate bloc$s of memory t!e new operator.#!is operator allocates memory for a given si0e and returns a pointerto its starting point. C%% also provides delete, to release t!e memoryallocated by new. #!e pointer returned by t!e newoperator need notbe typecasted.

    e.g.

    c!ar arrIJ/ ++ ompiletime allocation of an array

    c!ar Oarr/ ++ haracter pointer

    arr ne c!arIsi0eJ/ ++Run time allocation of an//array. +i%e can be a//constant or a variable.

    )n t!e above example, newreturns a pointer to a bloc$ of si0ebytes. )t is synonymous it! declaring a c!aracter array.

  • 8/14/2019 OOP- Notes.doc

    60/190

    c!ar Ocp/

    cp ne c!ar/ ++ 4ne character only.delete some/ ++ &elease memory.

    delete d4/c!ar Optr , Ostr Ht!e s!y is blue H/

    ptr ne c!ar Istrlen=str>%J/ ++ haracter array

    if= ptr Z >

    strcpy=ptr,str>/*

    *else

    printf=H not enoug! memory H>/

    struct date int dd,mm,yy//

    date Odp ne date/ ++ #!is allocated a newstructure++ to t!e pointer variable dp

    printf=H enter day H>/scanf=HWdE,dp-dd>/*

    94% ' 4he cin and cout objects

    )n C%% t!e $eyord cinit! t!e extraction operator H H isused to accept t!e input and t!e $eyord cout it! t!e insertionoperator H NN H is used to display string literals and values, in place ofscanf=> and printf=> functions of C.

  • 8/14/2019 OOP- Notes.doc

    61/190

    e.g.

    int ivar/float fvar/c!ar cvar/c!ar nameIJ/

    cin ivar /cin fvar cvar name/

    coutNN H ivar H NN ivar NN endl/coutNN H fvar H NNfvar NN H cvar H NN cvar NN name/

    )t is clear in t!e above example, !o e can accept and displayvariables. e can also concatenate various variables, using t!einsertion operator and extraction operator. !ile displaying, if yourite some text in t!e @uotes t!ey are displayed as it is. Fnot!ermanipulator endl can be used to end t!e line and get t!e cursor bac$to next line. e ill study about t!ese in detail in later sessions.

    #!is session introduced t!e concept of 'b(ect-'riented&rogramming. ''& improves upon t!e deficiencies of t!e traditionalstructured programming. ;ata abstraction, encapsulation and data!iding are some of t!e bu00ords of ''&. ''&, as seen, can be

    implemented in many languages. C%% is t!e most idely amongstt!em. )t is based on t!e C language and is t!us a complete superset oft!e original C language. Some additional features of C%% languageere covered in t!is session. #!e actual implementation features arecovered from next session onards.

    5ercises

    . F& to sort an array of strings. 2se ne and delete operators.

    3. F& to rite a program to find t!e factorial of a number usingrecursion. )f e do not accept t!e number from t!e user to findt!e factorial, t!en alays print t!e factorial of 8. 2se defaultargument met!ods.

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

    180

  • 8/14/2019 OOP- Notes.doc

    62/190

    Session

    Classes and -ects

    During this session you will learn about:

    Structures Revisited.

    )ntroduction to class.

  • 8/14/2019 OOP- Notes.doc

    63/190

    t!is ne data type can t!en be declared and used li$e basic datatypes.

    e.g.

    struct Student

    int Rollno/c!ar KameI4J/int ar$sI1J/float percent/

    /

    #!e above example depicts structure called students it!enclosed data variables. #!e $eyord struct is used to define astructure template. Student is a name or tag. #!e variables of t!is typecan be declared as follos *

    struct Student s,s3/

    Ior J

    )n C%% you can even omit t!e struct tag and declare t!evariables as,

    Student s = , HSan$etE , 3,,5,8,4,1, 54./Student s3,(ac$/Student Osptr s/Student sIJ/

    )n C%% , functions also can be declared in a structure template.#!ese functions are called as member functions.

    e.g.

    struct Student

    int Rollno/c!ar KameI4J/int ar$sI1J/float percent/

    void Uetdetails=>/

    182

  • 8/14/2019 OOP- Notes.doc

    64/190

    void &utdetails=>/int Clac&ercent=>/

    /

    #!ere are t!ree functions in t!e template given above. #!esefunctions !ave been incorporated in t!e structure definition to ma$e ita fundamental unit. #!e building toget!er of data and t!e functionst!at operate on t!at data is called as data encapsulation. But t!eproblem is t!at t!e member variables of t!is structure can be accessedby functions ot!er t!an t!e ones declared in t!e structure template.#!is direct access of member variables of a structure by functionsoutside t!e structure is not !at ''& !as to offer. #!e actual ''&met!odology in t!is regard is implemented in C%% not by t!e structuredata type, but by t!e data type class.#!e data type class is (ust li$estructures, but it! a difference. )t also !as some access specifier,

    !ic! controls t!e access to member variables of a class .

    8.3. )ntroduction to Classes

    'b(ect-oriented programming =''&> is a conceptual approac! todesign programs. )t can be implemented in many languages, !et!ert!ey directly support ''& concepts or not. #!e C language also can beused to implement many of t!e ob(ect-oriented principles. /

    183

  • 8/14/2019 OOP- Notes.doc

    65/190

    *

    private* ++ 4ptionaltype memberLvariableLname/

    *type memberLfunctionLname=>/*

    /

    #!e $eyord class is used to define a class template. #!e privateand public sections of a class are given by t!e $eyords !private" and!public"respectively. #!ey determine t!e accessibility of t!e members.Fll t!e variables declared in t!e class, !et!er in t!e private or t!e

    public section, are t!e members of t!e class. Since t!e class scope isprivate by default, you can also omit t!e $eyord private. )n suc!cases you must declare t!e variables before public, as riting publicoverrides t!e private scope of t!e class.

    e.g.

    class tagLname

    type memberLvariableLname/ ++ private

    *type memberLfunctionLname=>/ ++ private*

    public * ++ 6usttype memberLvariableLname/*type memberLfunctionLname=>/*

    /

    #!e variables and functions from t!e public section areaccessible to any function of t!e program.

  • 8/14/2019 OOP- Notes.doc

    66/190

    e.g.

    class player

    public * void getstats=void>/void s!ostats=void>/int noLplayer/

    private *c!ar nameI8J/int age/int runs/int tests/float average/

    float calcaverage=void>/ /

    #!e above example models a cric$et player. #!e variables in t!eprivate section name, age, runs, !ig!est, tests, and average can beaccessed only by member functions of t!e class calcaverage=>,getstats=> and s!ostats=>. #!e functions in t!e public section -getstats=> and s!ostats=> can be called from t!e program directly ,but function calcaverage=> can be called only from t!e memberfunctions of t!e class getstats=> and s!ostats=>.

    it! information !iding one need not $no !o actually t!e datais represented or functions implemented. #!e program need not $noabout t!e c!anges in t!e private data and functions. #!einterface=public> functions ta$e care of t!is. #!e ''& met!odology is to!ide t!e implementation specific details, t!us reducing t!ecomplexities involved.

    .. Classes and -ects

    Fs seen earlier, a class is a ve!icle to implement t!e ''&

    features in t!e C%% language. 'nce a class is declared, an ob'ect oft!at type can be defined. Fn ob'ectis said to be a specific instance of aclass (ust li$e ^aruti car is an instance of a ve!icle or pigeon is t!einstance of a bird. 'nce a class !as been defined several ob(ects oft!at type can be declared. :or instance, an ob(ect of t!e class definedabove can be declared it! t!e folloing statement*

    player Sac!in, ;ravid, ^o!an /

    185

  • 8/14/2019 OOP- Notes.doc

    67/190

    I'rJ

    class player Sac!in , ;ravid, ^o!an /

    !ere Sac!in and ;ravid are to ob(ects of t!e class player. Bot! t!eob(ects !ave t!eir on set of member variables. 'nce t!e ob(ect isdeclared, its public members can be accessed using t!e dot operatorit! t!e name of t!e ob(ect. e can also use t!e variable noLplayer int!e public section it! a dot operator in functions ot!er t!an t!efunctions declared in t!e public section of t!e class.

    e.g.

    Sac!in.getstats=>/

    ;ravid.s!ostats=>/^o!an.noLplayer /

    .". Pu-lic, Pri0ate and Protected mem-ers'

    Class members can eit!er be declared in publicA,AprotectedA or int!e privateA sections of t!e class. But as one of t!e features of ''& isto prevent data from unrestricted access, t!e data members of t!eclass are normally declared in t!e private section. #!e memberfunctions t!at form t!e interface beteen t!e ob(ect and t!e program

    are declared in public section = ot!erise t!ese functions can not becalled from t!e program >. #!e member functions !ic! may !avebeen bro$en don furt!er or t!ose, !ic! do not form a part of t!einterface, are declared in t!e private section of t!e class. By default allthe members of the class are private. #!e t!ird access specifierprotected" t!at is not used in t!e above example, pertains to t!emember functions of some ne class t!at ill be in!erited from t!ebase class. Fs far as non-member functions are concerned,private andprotected are one and t!e same.

    .#. 8em-er Functions of a Class

    F member function of t!e class is same as an ordinary function.)ts declaration in a class template must define its return value as ellas t!e list of its arguments. Tou can declare or define t!e function int!e class specifier itself, in !ic! case it is (ust li$e a normal function.But since t!e functions it!in t!e class specifier is considered inlinebyt!e compiler e s!ould not define large functions and functions it!

    186

  • 8/14/2019 OOP- Notes.doc

    68/190

    control structures, iterative statements etc s!ould not be ritten insidet!e class specifier.

    to specify t!e class to !ic! it belongs. #!e syntax is*

    returnLtype classLname ** functionLname =parameter list>

    *

    e.g.

    void player ** getstats =void>

    *

    void player ** s!ostats =void>

    **

    #!is notation indicates t!at t!e functions getstats => ands!ostats=> belong to t!e class player.

    .. Passing and /eturning -ects

    'b(ects can be passed to a function and returned bac$ (ust li$enormal variables. !en an ob(ect is passed by content , t!e compiler

    creates anot!er ob(ect as a formal variable in t!e called function andcopies all t!e data members from t!e actual variable to it. 'b(ects canalso be passed by address, !ic! ill be discussed later.

    e.g.

    class c!ec$

    187

  • 8/14/2019 OOP- Notes.doc

    69/190

  • 8/14/2019 OOP- Notes.doc

    70/190

  • 8/14/2019 OOP- Notes.doc

    71/190

    player Sac!in/

    Sac!in.getstats=>/

    Sac!in.s!ostats=>/

    player O;ravid/

    ;ravid ne player/

    ;ravid-getstats=>/;ravid-s!ostats=>/

    .. 5rra of -ects

    Fs seen earlier, a class is a template, !ic! can contain dataitems as ell as member functions to operate on t!e data items.Several ob(ects of t!e class can also be declared and used. Flso, anarray of ob(ects can be declared and used (ust li$e an array of anyot!er data type. Fn example ill demonstrate t!e use of array ofob(ects.

    e.g.

    class student public *

    void getdetails=>/void printdetails=>/

    private *int rollno/c!ar nameI34J/int mar$sI1J/float percent/

    /

    void student ** getdetails=> int ctr,total/

    cout NN Eenter rollnoE/cin rollno /

    190

  • 8/14/2019 OOP- Notes.doc

    72/190

    cout NN Eenter nameE/cin name/

    cout NN E enter 1 mar$s H /for= ctr /ctr N 1 / ctr%% > cin mar$sIctrJ/ total total % mar$sIctrJ/

    percent total + 1/

    void student ** printdetails =>cout NN rollno NN name NN percent /

    void main=>

    student recordsI4J/ int x/

    cout NN H

    recordsIiJ.getdeatils=>/for = int i / iN x/ i%%>

    recordsIiJ.printdeatils=>/

    Fs can be seen above, an array of ob(ects is declared (ust li$eany ot!er array. ^embers of t!e class are accessed, using t!e arrayname @ualified by a subscript.

    #!e statement,

    191

  • 8/14/2019 OOP- Notes.doc

    73/190

    recordsIyJ.printdetails=>/

    invo$es t!e member funs printdetails=> for t!e ob(ect given by t!e

    subscript y. :or different values of subscript, it invo$es t!e samemember function, but for different ob(ects.

    .1. 4he S$ecial Pointer this=

    !en several instances of a class come into existence, itnaturally follos t!at eac! instance !as its on copy of membervariables. )f t!is ere not t!e case, t!en for obvious reasons it ould

    be impossible to create more t!an one instance of t!e class. 'n t!eot!er !and, even t!oug! t!e class member functions are encapsulatedit! t!e data members inside t!e class definition, it ould be veryinefficient in terms of memory usage to replicate all t!ese memberfunctions and store t!e code for t!em it!in eac! instance.Conse@uently, only one copy of eac! member function per class isstored in memory, and must be s!ared by all of t!e instances of t!eclass.

    But t!is poses a big problem for t!e compiler*

  • 8/14/2019 OOP- Notes.doc

    74/190

    class tryLt!is public *

    void print=>/

    tryLt!is add=int>/

    private *int ivar/

    /

    void print=>

    cout NN ivar/cout NN t!is - ivar /

    #!e function print refers to t!e member variable ivar directly.Flso, an explicit reference is made using t!e this pointer. #!is specialpointer is generally used to return t!e ob(ect, !ic! invo$ed t!emember function. :or example,

    void main=> tryLt!is t,t3/

    t3 t.add=5>/t3.print=>/

    tryLt!is tryLt!is ** add=int v>

    ivar ivar % v/return = Ot!is>/

    )n t!e above example if ivar for t is and value in

    v is 3, t!en t!e function add=> adds t!em and ivar for t becomes 3 .e ant to store t!is in anot!er ob(ect t3, !ic! can be done byreturning t!e ob(ect t using Ot!is to t3. #!e result of t3.print=> no illbe 3.

    :ereferencing the Pointer this

    193

  • 8/14/2019 OOP- Notes.doc

    75/190

    Sometimes a member function needs to ma$e a copy of t!einvo$ing instance so t!at it can modify t!e copy it!out affecting t!eoriginal instance. #!is can be done as follos *

    tryLt!is temp=Ot!is>/tryLt!is temp Ot!is /

    )n ''& emp!asis is on !o t!e program represents data. )t is adesign concept it! less emp!asis on operational aspects of t!eprogram. #!e primary concepts of ''& is implemented using classand ob(ects. F class contains data members as ell as functionmembers. #!e access specifiers control t!e access of data members.'nly t!e public members of t!e class can access t!e data membersdeclared in private section. 'nce class !as been defined, many ob(ects

    of t!at class can be declared. ;ata members of different ob(ects of t!esame class occupy different memory area but function members ofdifferent ob(ects of t!e same class s!are t!e same set of functions.#!is is possible because of t!e internal pointer Ot!isA !ic! $eepstrac$ of !ic! function is invo$ed by !ic! ob(ect.

    5ercises:

    . ;efine a class to model a ban$ing system. #!e functionmembers s!ould allo initiali0ing t!e data members, a @uery tofacilitate for account and a facility to deposit and it!dra from

    t!e account. F& to implement t!e same.

    3. Create a class called #ime t!at !as separate int member data for!ours, minutes and seconds. rite functions for accepting timeand displaying time.

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

    Session "

    Constructor and ;estructor :unctions

    During this session you will learn about :

    Futomatic initiali0ation of data members - constructors

    Constructor it! one argument, multi arguments

    2sing t!e constructor

    194

  • 8/14/2019 OOP- Notes.doc

    76/190

    ;estructor

    ;efault constructor and destructor

    Since C%% supports t!e concept of user-defined classes and t!esubse@uent initiations of t!ese classes, it is important t!at initiali0ationof t!ese instantiations be performed so t!at t!e state of any ob(ectdoes not reflect H garbageE. 'ne of t!e principles of C%% is t!atob(ects $no !o to initiali0e and cleanup after t!emselves. #!isautomatic initiali0ation and clean up is accomplis!ed by to memberfunctions t!e constructor and t!e destructor.

    ".1 Constructors

    By definition, a constructor function of some class is a memberfunction t!at automatically gets executed !enever an instance of t!eclass to !ic! t!e constructor belongs comes into existence. #!eexecution of suc! a function guarantees t!at t!e instance variables oft!e class ill be initiali0ed properly.

    F constructor function is uni@ue from all ot!er functions in aclass because it is not called using some instance of t!e class, but isinvo$ed !enever e create an ob(ect of t!at class.

    F constructor may be overloaded to accommodate many

    different forms of initiali0ation for instances of t!e class. i.e. for asingle class many constructors can be ritten it! different argumentlists .

    Snta6 rules for . , const= in !ic! you can not ma$ec!anges>.

    )t s!ould !ave public or protected access it!in t!e class. 'nly invery rare circumstances t!e programmers declare it in privatesection.

    195

  • 8/14/2019 OOP- Notes.doc

    77/190

    e.g.

    class boxclass

    public *boxclass = int x, int y, int x3, int y3>/void disp=void>/

    private *int x, y/int x3, y3 /

    /

    boxclass**boxclass=int ax,int ay, int ax3, int ay3>

    x ax /y ay /x3 ax3 /y3 ay3 /

    ".2.1 7sing the Constructor

    #!ere are basically t!ree ays of creating and initiali0ing t!e

    ob(ect. #!e first ay to call t!e constructor is eplicitlyas *

    boxclass bigbox boxclass = ,,34,69>/

    #!is statement creates an ob(ect it! t!e name bigbox andinitiali0es t!e data members it! t!e parameters passed to t!econstructor function. #!e above ob(ect can also be created it! animplicitcall to t!e constructor *

    boxclass bigbox=,,34,69>/

    Bot! t!e statements given above are e@uivalent. Tet, anot!eray of creating and initiali0ing an ob(ect is by direct assignment of t!edata item to t!e ob(ect name.But# this approach wor0s if there is onlyone data item in the class. #!is is obvious because e cannot assignmore t!an one value at a time to a variable.

    e.g.

    196

  • 8/14/2019 OOP- Notes.doc

    78/190

    class counter public *

    counter = int c> ++ constructor.

    count c//

    private *int count/

    /

    e can no create an ob(ect as,

    counter cnt /

    )n t!e above example , ob(ect cnt is initiali0ed by a value 0ero att!e time of declaration. #!is value is actually assigned to its datamember count. #!is is t!e t!ird ay to initiali0e an ob(ectAs datamember. #!us, all t!e folloing statements to initiali0e t!e ob(ects oft!e class counter are e@uivalent*

    counter c=3>/counter c counter=5>/

    counter c /

    'nce t!e constructor for a class !as been declared and defined,t!e program must use it. )n ot!er ords, ob(ects cannot bedeclaring it!out initiali0ing t!em. :or instance, in t!e aboveexample, an ob(ect of class counter !as to be declared andinitiali0ed in one of t!e t!ree ays given above. 2ninitiali0edob(ects li$e *

    counter cx,cy/

    are not alloed.

  • 8/14/2019 OOP- Notes.doc

    79/190

    e.g.

    class counter public *

    counter = int c > ++ onstructor.

    count c//

    private *int count/

    /

    )n t!e example above, if t!e actual argument is not given, t!ent!e value of t!e formal variable c in t!e constructor defaults to 0ero.#!us, declaration of ob(ects of t!is class can be uninitiali0ed as ell.

    counter c=3>/counter c3 counter=5>/counter c5 /counter c8,c4/

    F constructor can be used to generate temporary instances asell , as given belo *

    counter create= int cc>

    return counter=c>/

    Fn array of ob(ects can be initiali0ed at t!e time of declaration. F

    constructor !as to be provided foe t!e same. #!e example given belouses t!e class employee to illustrate t!is.

    class employee public *

    employee=c!ar On, int a, double s>/

    198

  • 8/14/2019 OOP- Notes.doc

    80/190

    private*c!ar nameI8J/int age/double salary/

    /

    employee ** employee =c!ar On , int a, double s>

    strcpy= name, n >/age a/salary s/

    void main=>

    employee ?I5J employee=HsanatE,34,91>, employee=Hsan$etE,54,31>, employee=HpriyaE,37,31> /

    ".3. :estructors

    F destructor function gets executed !enever an instance of t!e

    class to !ic! it belongs goes out of existence. #!e primary usage of adestructor function is to release memory space t!at t!e instancecurrently !as reserved.

    Snta6 rules for .

    )t is declared it! no return type = not even void > since it cannot

    ever return a value. )t cannot be static, const or volatile.

    )t ta$es no input arguments , and t!erefore cannot beoverloaded.

    )t s!ould !ave public access in class declaration.

    199

  • 8/14/2019 OOP- Notes.doc

    81/190

    Uenerally t!e destructor cannot be called explicitly =directly>from t!e program. #!e compiler generates a class to destructor !ent!e ob(ect expires. Class destructor is normally used to clean up t!emess from an ob(ect. Class destructors become extremely necessary

    !en class constructor use t!e new operator, ot!erise it can begiven as an empty function.

    \employee=>/

    /

    ".". 5 Constructi0e %6am$le

    Consider an example , to model a user-defined data type forstrings. #!e ob(ect simulates a c!aracter array = string > using ac!aracter pointer and an integer variable for its actual si0e, !ic! canbe determined at its run-time. #!e ob(ect doesnAt use a c!aracter array, since it may impose a limit on t!e number of c!aracters t!at can be

    stored.

    e.g.

    include Niostream.! include N string.!

    class string

    200

  • 8/14/2019 OOP- Notes.doc

    82/190

    public *

    string = c!ar Os>/\string=>/

    void putstr=>/private *

    c!ar Ocptr/int si0e/

    /

    void main=void> string s=H /

    string s3 H elcome to C%% DnE/ string s5 string = H its fun DnE>/

    s.putstr=>/s3.putstr=>/s5.putstr=>/

    string**string=c!ar Os>

    si0e strlen=s>/

    cptr ne c!arIsi0e % J/strcpy=cptr,s>/

    string**\string=> delete cptr/

    void string**putstr=>

    cout NN cptr/

    #!e class defined in t!e above example contains a c!aracterpointer, !ic! allocates memory at runtime, after determining t!eactual si0e re@uired. #!is programme demonstrates t!e use of classalong it! t!e constructor and destructor to create a user defined data

    201

  • 8/14/2019 OOP- Notes.doc

    83/190

    type String. #!e constructor function contains a default argument ofnull c!aracter, !ic! ill be assigned to t!e variable cptr in t!eabsence of an actual parameter. #!e destructor uses t!e deleteoperator to release t!e memory allocated by t!e constructor .

    F class can contain data members as ell as function members.F member function is t!e only ay to access t!e private sectionmembers of a class. :or initiali0ing t!e data members of t!e class, emay rite a function (ust li$e any ot!er function. But t!en, e !ave toinvo$e t!is function explicitly. C%% provides a special function calledconstructor. #!is function is called automatically !en e create anob(ect. )t contains code to initiali0e t!e member variables using t!eformal parameters if t!ey are passed via ob(ects. )f e rite suc! afunction t!en e must pass parameters eac! time. #o evade t!is

    problem e can rite many constructors to give some flexibility tocreate ob(ects it! different parameter lists. e can also use defaultarguments in t!e constructor.

    C%% also provides a special member function called destructor,!ic! is called automatically !en an ob(ect expires as per t!e scoperules. Bot! constructor and destructors do not !ave return types, noteven void. #!e destructor cannot !ave any parameters as ell.

    %6ercises

    . Create a class called #ime t!at !as a separate data members forday, mont! and year. F constructor s!ould be used to initiali0et!ese members. #!en rite a function to add t!ese dates andstore t!e result in a t!ird ob(ect and display it.

    3. F& to add co-ordinates of t!e plane. #!e class contains x and yco-ordinates. Create t!ree ob(ects. 2se a constructor to passone pair of co-ordinates and a function to accept t!e second

    pair. Fdd t!ese variables of to ob(ects and store t!e result int!e t!ird.

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

    Session #

    202

  • 8/14/2019 OOP- Notes.doc

    84/190

    $erator 0erloading

    During this session you will learnabout*

    )ntroduction to 'perator 'verloading.

    'perator 'verloading :undamentals.

    )mplementing t!e operator functions.

    Rules for overloading t!e operators.

    &ointer oddities =assignment> and 'perator 'verloading.

    Copy Constructor =to solve t!e problem of initiali0ation>.

    Conversion functions.

    Fll computer languages !ave built in types li$e integers, realnumbers, c!aracters and so on. Some languages allo us to create ouron data types li$e dates, complex numbers, co-ordinates of a point.'perations li$e addition, comparisons can be done only on basic datatypes and not on derived =user-defined> data types. )f e ant tooperate on t!em e must rite functions li$e compare =>, add =>.

    e.g.

    if =compare =v, v3> >

    **

    !ere v and v3 are variables of t!e ne data type and compare => isa function t!at ill contain actual comparison instructions forcomparing t!eir member variables. **

    !ere t!e operation of comparing t!em is defined in a memberfunction and associated it! comparison operator=>.

    #!e ability to create ne data types, on !ic! direct operationscan be performed is called as extensibility and t!e ability to associatean existing operator it! a member function and use it it! t!eob(ects of its class, as its operands, is called as 'perator 'verloading.

    203

  • 8/14/2019 OOP- Notes.doc

    85/190

    'perator 'verloading is one form of Polymorphism ,animportant feature of ob(ect-oriented programming .&olymorp!ismmeans one t!ing !aving many forms, i.e. !ere an operator can be

    overloaded to perform different operations on different data types ondifferent contexts. 'perator 'verloading is also called operationalpolymorp!ism. Fnot!er form of polymorp!ism is function overloading.

    #.1. $erator 0erloading Fundamentals

    #!e C language uses t!e concept of 'perator 'verloadingdiscreetly. #!e asteris$ =O> is used as multiplication operator as ell asindirection =pointer> operator. #!e ampersand => is used as addressoperator and also as t!e bitise logical FK;A operator. #!e compiler

    decides !at operation is to be performed by t!e context in !ic! t!eoperator is used.

    #!us, t!e C language !as been using 'perator 'verloadinginternally. Ko, C%% !as made t!is facility public. C%% can overloadexisting operators it! some ot!er operations. )f t!e operator is notused in t!e context as defined by t!e language, t!en t!e overloadedoperation, if defined ill be carried out.:or example, in t!e statement

    x y % 0/

    )f x, y and 0 are integer variables, t!en t!e compiler $nos t!eoperation to be performed. But, if t!ey are ob(ects of some class, t!ent!e compiler ill carry out t!e instructions, !ic! ill be ritten fort!at operator in t!e class.

    #.2. Im$lementing $erator Functions

    #!e general format of t!e 'perator function is*

    returnLtype operator o$ = argument list >/

    !ere opis t!e symbol for t!e operator being overloaded. 'p!as to be a valid C%% operator, a ne symbol cannot be used.

    e.g.

    "et us consider an example !ere e overload

    204

  • 8/14/2019 OOP- Notes.doc

    86/190

    unary arit!metic operator %%A.

    class Counter

    public * Counter=>/void operator%%=void>/

    private *int Count/

    /

    Counter**Counter=>

    Count /

    void Counter**operator%%=void>

    %% Count /

    void main=> Counter c/

    c%%/ ++ increments Count to %%c/ ++ increments Count to 3

    )n main=> t!e increment operator is applied to a specific ob(ect.#!e function itself does not ta$e any arguments. )t increments t!e datamember Count. Similarly, to decrement t!e Counter ob(ect can also becoded in t!e class definition as*

    void operator--=void>

    -- Count /

    and invo$ed it! t!e statement

    --c/ or c--/

    205

  • 8/14/2019 OOP- Notes.doc

    87/190

    )n t!e above example , t!e compiler c!ec$s if t!e operator isoverloaded and if an operator function is found in t!e class descriptionof t!e ob(ect, t!en t!e statement to increment gets converted, by t!ecompiler, to t!e folloing*

    c.operator%%=>/

    #!is is (ust li$e a normal function call @ualified by t!e ob(ectAsname. )t !as some special c!aracters = %%> in it. 'nce t!is conversionta$es place, t!e compiler treats it (ust li$e any ot!er member functionfrom t!e class. e !aveto return values to t!e calling function.

    Counter Counter ** operator%%=void>

    Counter temp/

    temp.Count %% Count /return = temp >/

    void main=> Counter c,c3/

    c c3 %%/ ++increments to , t!en assigns.

    )n t!is example , t!e operator function creates a ne ob(ecttemp of t!e class Counter, assigns t!e incremented value of Count tot!e data member of temp and returns t!e ne ob(ect. #!is ob(ect isreturned to main=>. e can do t!is in anot!er ay by creating anameless temporary ob(ect and return it.

    class Counter

    206

  • 8/14/2019 OOP- Notes.doc

    88/190

    public *

    Counter=>/ ++ C'KS#R2C#'R )# ++ C'KS#R2C#'R )#< FRU2^?K#

    Count c/

    Counter Counter**operator%%=void>

    %% Count / return Counter=Count>/

    'ne c!ange e can see is a constructor it! one argument. Kone temporary ob(ect is explicitly created. /

    207

  • 8/14/2019 OOP- Notes.doc

    89/190

    Consider a class C'^&"? for Complex numbers. )t ill !ave areal and an imaginary member variable. /

    private*int real, imaginary/

    /

    Suppose t!at C, C3 and C5 are ob(ects of t!is class.Symbolically addition can be carried out as

    C5 C % C3/

    #!e actual instructions of t!e operator are ritten in a specialmember function.

    e.g.

    C'^&"? C'^&"? ** operator%= C'^&"? C3>

    C'^&"? temp/

    temp.real real % C3.real/temp.imaginary imaginary % C3. imaginary/return =temp>/

    #!e above example s!os !o 'perator 'verloading isimplemented. )t overloads H%E operator to perform addition on ob(ectsof C'^&"? class. .

    #.3. /ules for o0erloading an o$erator

    208

  • 8/14/2019 OOP- Notes.doc

    90/190

    #!is summari0es t!e most important points you need to $no inorder to do operator function overloading.

    #!e only operators you may overload are t!e ones from t!eC%% list and not all of t!ose are available. Tou cannot

    arbitrarily c!oose a ne symbol =suc! as > and attempt toHoverload it.

    Start by declaring a function in t!e normal function fas!ion,but for t!e function name use t!e expression*

    'perator op !ere opis t!e operator to be overloaded. Tou may leave

    one or more spaces before op. #!e pre-defined precedence rules cannot be c!anged. i.e. you

    cannot, for example, ma$e binary %A !ave !ig!er precedencet!an binary OA. )n addition, you cannot c!ange t!eassociativity of t!e operators.

    #!e unary operators t!at you may overload are*;D

    indirect mem-er o$eratorE

    not address

    Adereference

    +$lus

    - minus++ $refi6 increment++ $ostfi6 increment ($ossi-le in54 4

    0ersion 2.1);;

    $ostfi6 decrement;; $refi6 decrement ($ossi-le in54 4

    0ersion 2.1)G one=s com$lement

    4he -inar o$erators that ou ma o0erload are'(), H, ne

  • 8/14/2019 OOP- Notes.doc

    91/190

    .A direct $ointer to mem-er'' sco$e resolutionQ' ternar

    9o default arguments are allo

  • 8/14/2019 OOP- Notes.doc

    92/190

    String''String () JJ C9S4/7C4/ UI4BRJJ 9 5/V78%94S

    sH M T

    String'' String( char str H ) JJ C9S4/7C4/ UI4BR

    JJ 9% 5/V78%94strc$(s,str)

    T

    0oid String'' $utstr()JJ F79C4I9 4 P/I94 S4/I9VR

    cout s T

    String String '' o$erator+(String s2)R String tem$

    strc$(tem$.s,s)strcat(tem$.s,s2.s)

    return (tem$)T

    String String '' o$erator+M(String s2)R

    strcat(s,s2.s)return (Athis)

    T

    int String''o$erator (String s2)R

    return (strcm$ (s, s2.s ) )

    T

    int String''o$erator D (String s2)

    211

  • 8/14/2019 OOP- Notes.doc

    93/190

    Rreturn (strcm$ (s, s2.s ) D )

    T

    int String''o$erator MM (String s2)Rreturn (strcm$ (s, s2.s ) MM )

    T

    int String''o$erator EM (String s2)R

    return (strcm$ (s, s2.s ) EM )

    T

    0oid main()R

    String s1 M W

  • 8/14/2019 OOP- Notes.doc

    94/190

    if( s" s# )R

    s".$utstr()

    cout X Xs#.$utstr()T

    else if( s" D s# )R

    s".$utstr()cout X D X

    s#.$utstr()T

    else if( s" MM s# )R

    s".$utstr()cout X M Xs#.$utstr()

    Telse if( s" EM s# )R

    s".$utstr()cout X X

    s#.$utstr()T

    T

    ut$ut'

    S1 M

  • 8/14/2019 OOP- Notes.doc

    95/190

    class StringR $u-lic '

    String (char As M WX) JJC9S4/7C4/R

    si?e M strlen(s)

    c$tr M ne< char Hsi?e + 1

    strc$(c$tr,s)T

    GString() R

    delete c$trT

    0oid $utstr()JJ F79C4I9 4 P/I94 S4/I9V

    R

    cout c$tr T

    $ri0ate 'char Ac$tr

    int si?e

    T

    0oid main()R String s1(Whello students W)

    String s2

    s2 M s1 JJ 5ssignments1.$utstr()s2.$utstr()

    T

    214

  • 8/14/2019 OOP- Notes.doc

    96/190

    4he constructor function allocates a string and co$ies thecontents of its