Cpp Study Notes-libre

  • Upload
    cseritm

  • View
    230

  • Download
    0

Embed Size (px)

Citation preview

  • 8/10/2019 Cpp Study Notes-libre

    1/108

    1

    OBJECT ORIENTED PROGRAMMING USING C++

    1.1 The Evolution of C++:Computer languages have come a long way since the 1940s. Back then, scientists

    punched instructions in to mammoth, room-sied computer systems. !hese instructions werelong series o" eroes and ones. !hese machine language instructions are called the frstgenerationo" computer languages.

    !he 19#0s saw the emergence o" the second generation computer languages-assembly language-easier to write than machine language $ut still e%tremely complicated "ora lay person. &owever, the computer could still understand only machine language.

    !here"ore, the assem$ler so"tware was developed to translate the code written in assem$lylanguage into machine language.

    'n 19(), *artin +ichard developed a language called BC "or writing operatingsystems. n operating system is a set o" programs that manages the resources o" a computerand its interactions with users.

    !he era o" the third generation o" computer languages had arrived. 'n 19)0s /en

    !hompson modied BC to create a new language called B. working "or Bell a$oratories,!hompson teamed up with ennis +itchie and wrote an early version o" the 2ni% operatingsystem "or a 3C -) computer.

    ennis +itchie was working on a proect to "urther develop the 2ni% operating system.&e wanted a low-language, like the assem$ly language, the could control hardware e5ciently.t the same time, he wanted the language to provide the "eatures o" a high level language,that is, it should $e a$le to run on di6erent types o" hardware. B had per"ormance draw$acks,so in 19)7, he rewrote B and called in C.

    !here"ore, C is categoried as $oth a second and third generation language. !hompsonand +itchie rewrote the 2ni% operating system in C. 'n the years that "ollowed, C was widely

    accepted and used over di6erent hardware plat"orms. 'n 1989, the American NationalStandards Institute(:';, along with the 'nternational :tandards >language. 'n his own words , ? C>> was designed primal so that my "riends an ' would nothave to program in assem$ly, C, or various modern high-level languages. 'ts main purposewas to make writing "ood programs easier and more pleasant "or the individual programmer@.=Barne :troustup The C++ Programming Language !hird 3dition. +eading, *A dditionesley u$lishing Company 199);. C>> was originally known as C with classes as twolanguages contri$uted to its design. C which provided low-level "eatures, and simula!" whichprovided theclass concept.

    !he C>> language is a superset o" C. ike the C language, C>> is compact and can $eused "or system programming. 't can use e%isting C so"tware libraries# =i$raries arecollections o" programs that you can reuse in your program.; C>> has o$ect-orientedprogramming = is called a hy$rid language $ecause it can $e used $oth as a procedural language like C andas an o$ect-oriented language like :imula(), other o$ect-oriented languages includeSmalltal$andAda#

    'n 1990s, the :'D':< committee $egan working on a standard version o" the C>>language. By Eune 1998,the committee had approved the Final ra"t 'nternational :tandard "orC>>. 't was released in the "orm o" a document. 't e%tended the language to includee%ceptions, templates, and the StandardTemplate Library = :!;.

  • 8/10/2019 Cpp Study Notes-libre

    2/108

    2

    Soft%!"e Evolution:

    !he so"tware evolution has had distinct phases or ?layers@ o" growth. !hese layers were$uilt up one $y one over the last ve decades as shown in gure. 3ach layer representing animprovement over the previous one.

    1, 0

    Machine language

    Assembly language

    Procedure-oriented

    Object oriented programming

    Fig. ayers o" computer so"tware

    Object-Oriented Programming =

  • 8/10/2019 Cpp Study Notes-libre

    3/108

    3

    'n a multi-"unction program, many important data items areplaced as $y all the "unctions. 3ach "unction may have its ownlocal data. Fig "unctions in a procedure-oriented program.

    global so that they may $eaccessedshows therelationship o" data and

    Jlo$al data Jlo$al data

    Function-1 Function-7 Function-H

    ocal data ocal data ocal data

    Fig- +elationship o" data and "unctions in procedural programming

    Jlo$al data are more vulnera$le to an inadvertent change $y a "unction. 'n a largeprogram it is very di5cult to identi"y what data is used $y which "unction.

    nother serious draw$ack with the procedural approach is that it does not model realworld pro$lems very well. !his is $ecause "unctions are action-oriented and do not reallycorresponding to the elements o" the pro$lem.

    :ome characteristics e%hi$ited $y procedure-oriented programming areA

    1. O/e't0O"iente( P"o*"!in* P!"!(i*:

    !he maor motivating "actor in the invention o" o$ect-oriented approach is to removesome o" the Kaws encountered in the procedural approach.

  • 8/10/2019 Cpp Study Notes-libre

    4/108

  • 8/10/2019 Cpp Study Notes-libre

    5/108

  • 8/10/2019 Cpp Study Notes-libre

    6/108

    !he entire set o" data and code o" an o$ect can $e made a user-dened data type withthe help o" a class.O/e't# !"e v!"i!/le of the t3$eclass.

  • 8/10/2019 Cpp Study Notes-libre

    7/108

    .

    '" f"uithas $een dened as a 'l!##, then the statement.

    f"uit appleLwill create an o$ect !$$le$elonging to the class f"uit.

    D!t!

    A/#t"!'tion !n( En'!$#ul!tion:

    $straction re"ers to the act o" representing essential "eatures without including the

    $ackground details or e%planations. Classes use the concept o" a$straction and aredened as a list o" a$stract attributes such as sie, weight and cost, and %unctions tooperate on these attri$utes.

    :ince the classes use the concept o" data a$straction, they are known as AbstractData Types=!;.

    !he attri$utes are sometimes called data members$ecause they hold in"ormation. !he"unctions that operate on these data are sometimes called methods or memberfunctions.

    En'!$#ul!tion: The %"!$$in* u$ of (!t! !n( fun'tion into ! #in*le unit ,'!lle('l!##- i# 2no%n !# encapsulation. The (!t! i# not !''e##i/le to the out#i(e %o"l(9!n( onl3 tho#e fun'tion# %hi'h !"e

    %"!$$e( in the 'l!## '!n !''e## it.!his instruction o" the data "rom direct access $y the program is called data hidingor information

    hiding.A/#t"!'tion fo'u#e# on the e##enti!l 'h!"!'te"i#ti'# of o/e't#Inhe"it!n'e:

    nheritance i# the $"o'e## /3 %hi'h o/e't of one 'l!## !'ui"e the $"o$e"tie#of o/e't# of

    't supports the concept o" hierarchical classifcation. For e%ample, the $ird ro$in is apart o" the class Kying $ird which is again a part o" the class $ird. !he principle$ehind this sort o" division is that

    each derived class shares common characteristics with the class "rom which it is derived as illustrated in

    g.!nothe"'l!##.C"e!te ! ne% 'l!## (e"ive( f"o the ol( 'l!##.

    Bird

    ttri$uteFeaturesay eggs

    Flying Bird on-FlyingBird

    ttri$ute

    MMMM ttri$ute

    MMMM MMMM

    +o$in :wallow enguin /iwi

    ttri$ute ttri$ute ttri$ute ttri$ute

    MMMM MMMM MMMM MMMM

    MMMM MMMM MMMM MMMM

    Fig- property inheritance

    'n

  • 8/10/2019 Cpp Study Notes-libre

    8/108

    !his is possi$le $y deriving new class "rom the e%isting one. !he new class will have thecom$ined "eatures o" $oth the class.

  • 8/10/2019 Cpp Study Notes-libre

    9/108

    /

    Pol3o"$hi#:

    Polymorphism i# !nothe" i$o"t!nt OOP 'on'e$t. Pol3o"$hi#9 ! G"ee2te"9 e!n# the!/ilit3 to t!2e o"e th!n one fo". An o$e"!tion !3 e6hi/it(i;e"ent /eh!vio"# in (i;e"ent

    !he $ehavior depends upon the types o" data used in the operation.

    For e%ample, consider the operation o" addition. For two num$ers, the operation willgenerate a sum. '" the operands are string, then the operation would produce a third

    string $y concatenation. !his process o" making an operator to e%hi$it di6erent $ehaviors in di6erent instances

    is known as operator overloading. 2sing a single "unction name to per"orm di6erent types o" tasks is known as function overloading!

    in#t!n'e#.

    Figure illustrates that a single "unction name can $e used to handle di6erent num$erand di6erent types o" arguments.

    :hape

    raw

    Circle o$ect Bo% o$ect !riangle o$ect

    raw =circle; raw =$o%; raw =triangle;

    Fig. I olymorphism

    olymorphism plays an important role in allowing o$ect having di6erent internalstructures to share the same e%ternal inter"ace. !his means that a general class o" operationmay accessed in the same manner even though specic actions associated with each

    operation may di6er. olymorphism is e%tensively used in implementing inheritance.

    Binding re"ers to the linking o" a procedure call to the code to $e e%ecuted in responseto the call.

    Dynamic "inding ,!l#o 2no%n !# l!te /in(in*- e!n# th!t the 'o(e !##o'i!te(%ith ! *iven$"o'e(u"e '!ll i# not 2no%n until the tie of the '!ll !t "un0tie.It i# !##o'i!te( %ith $ol3o"$hi# !n( inhe"it!n'e.

    "unction call associated with a polymorphic re"erence depends on the dynamic type o" that

    re"erence.D3n!i'Bin(in*:Consider the procedure ?draw@ in a$ove gure $y inheritanceL every o$ect will have

    this procedure. 'ts algorithms are, however, uniGue to each o$ect and so the draw procedure

    will $e redened in each class that denes the o$ect.

    n o$ect-oriented program consists o" a set o" o$ects that communicate with eachother. !he process o" programming in an o$ect-oriented language, there"ore, involvesthe "ollowing $asic stepsAi. Creating classes that dene o$ects and their $ehavior.ii. Creating o$ects "rom class denitions, andiii. 3sta$lishing communication among o$ects.

    A e##!*e fo" !n o/e't i# ! "eue#t fo" e6e'ution of ! $"o'e(u"e9 !n( the"efo"e %illinvo2e ! fun'tion ,$"o'e(u"e- in the "e'eivin* o/e't th!t *ene"!te# the (e#i"e("e#ult.

    Me##!*eP!##in*:

  • 8/10/2019 Cpp Study Notes-libre

    10/108

    &essage passing involves speci"ying the name o" the o$ect, the name o" the "unction=message; and

    the in"ormation to $e sent. 3%ampleA3mployee.salary=name;L

  • 8/10/2019 Cpp Study Notes-libre

    11/108

    o$ect-oriented.epending upon the "eatures they support, they can $e classied into the "ollowing twocategoriesA

  • 8/10/2019 Cpp Study Notes-libre

    12/108

    anguages that support programming with o$ects are said to $e o$ect-$asedprogramming languages. !hey do not support inheritance and dynamic $inding. da is a

    typical o$ect-$ased programming

    language.Object-oriented programming in'o"$o"!te# !ll of o/e't0/!#e( $"o*"!in*fe!tu"e# !lon* %itht%o !((ition!l fe!tu"e#9 n!el39 inhe"it!n'e !n( (3n!i'/in(in*. It@# #i$l3

    > , :malltalk and o$ect ascal andava. !here are a large num$er o" o$ect-$ased and o$ect-oriented programming languages.

    C++ STREAMS

    stream is a seGuence o" $ytes. !he sourcestream that provides data to the programis called the input stream and thedestination stream that receives output "rom the program iscalled the output stream. program e%tracts the $ytes "rom and input stream and inserts$ytes into an output stream.

    'nput :tream

    'nput 3%traction"rom

    evice input stream

    rogram

  • 8/10/2019 Cpp Study Notes-libre

    13/108

  • 8/10/2019 Cpp Study Notes-libre

    14/108

    UN4ORMATTED I?O OPERATIONS:

    !he "ollowing "unctions are used to implement the un"ormatted console 'D< operations.!hey are the mem$er "unctions o" the istream and ostream classes. :o, we should use the cinand cout o$ects withthe"unctions.

    In$ut fun'tion# ,i#t"e! 'l!##-Out$ut fun'tion# ,o#t"e!+'l!##-

    overload operator NN, overload operator OO,get= ;, put= ;,getline= ; write= ;

    Ove"lo!( o$e"!to" : 2sed to get input "rom the key$oard.

    S3nt!6 :'in v!"1 v!"& v!"n

    E6!$le : 'in 6 3 8

    *et, - :!his "unction is used to get input "rom the key$oard. e can use this "unction in two

    ways. 1. *et,'h!"- &. *et,voi(-

    S3nt!6 :'in.*et,v!"n!e- S3nt!6 :

    v!"n!+e F'in.*et, -

    E6!$le : 'h!" ' E6!$le : 'h!" ''in.*et,'- ' F 'in.*et, -

    *etline, - :!his "unction is used to get a line o" te%t asinput.S3nt!6 : 'in.*etline,v!"n!e9 #i8e-E6!$le : 'h!" n!e1H

    'in.*etline,n!+e9 1H-

    Ove"lo!( o$e"!to" :!his "unction is used to display the output on P2.

    S3nt!6 :'out v!"1 v!"& v!"n

    E6!$le :'out 6 3Th!n23ou

    $ut, - :!his "unction is used to display a single character as output on P2.

    S3nt!6 :'out.$ut,v!"n!+e-

    E6!$le : 'h!" ' F K8@

    'out.$ut,'-

    %"ite, - :!his "unction is used to display a line o" te%t as output on the screen.

    S3nt!6 :'out.%"ite,v!"n!e9#i8e-

    E6!$le :'h!" n!+eG1H F 5Th!n2

    LouJ'out.%"ite,n!e9 1H-

    4ORMATTED CONSOE I?O OPERATIONS

    Formatted console 'D< operations are used to "ormat the output o" a program. !hese

    "unctions are the mem$er "unctions o" io#class. :o, we should use the 'outo$ect "or usingthese "unctions.i. width= ;ii. prescision= ;iii. ll= ;iv. set"= ;

  • 8/10/2019 Cpp Study Notes-libre

    15/108

    v. unset"= ;%i(th, -: 2sed to speci"y the reGuired eld sie "or displaying an output value.S3nt!6 : 'out.%i(th,#i8e-

    & E6!$le : int ! F &

    'out.%i(th,-'out!

    $"e'i#ion, - : 2sed to speci"y the num$er o" digits to $e displayed a"ter the decimal point o"a Koat value.S3nt!6 : 'out.$"e'i#ion, #i8e-

    & & . 1 &E6!$le : int ! F &&.1&

    'out.$"e'i#ion,&-'out!

  • 8/10/2019 Cpp Study Notes-libre

    16/108

    10

    7ll, - : 2sed to speci"y a character that is used to ll the unused portion o" a eld.S3nt!6 : 'out.7ll, !"* -

    Q HE6!$le : int ! F QH

    'out.%i(th,-'out.7ll,K@-'out!

    #etf, - : 2sed to speci"y "ormat Kags that can control the "orm o" output display =such asle"t-usticationand right-ustication;

    Format reGuired Flag =arg1; Bit-eld =arg7;

    e"t-ustied output iosAAle"t iosAAadusteld+ight-ustied output iosAAright iosAAadusteldadding a"ter sign or$ase iosAAinternal iosAAadusteld

    :cientic notation iosAAscientic iosAAKoateld

    Fi%ed point notation iosAA%ed iosAAKoateld

    ecimal $ase iosAAdoc iosAA$aseeld

  • 8/10/2019 Cpp Study Notes-libre

    17/108

  • 8/10/2019 Cpp Study Notes-libre

    18/108

    11

    *anipulators and their meanings

    #et

    %

    ,-!ni$ul!to":

    0!akes integer type o" varia$le as its parameter. !he parameter species the width o"the column.

    E6!$le: 1. coutOO 17HOOendlL Out$ut:7. coutOO setw =H; OO 10L 17H

    10

    ,- !ni$ul!to":C>> displays values o" Koat and dou$le type with si% digits $y de"ault a"ter decimal point. By

    using the setprecision =; manipulator we can pass num$er o" digits we want to display

    a"ter#et$"e'i#ion

    decimal point.E6!$le: 1. coutOOsetprecision=H;L Out$ut:

    7. coutOO sGrt =H; OO endlL1.)H7 =the value o" i#1.Q&HHHQV;

    #et7ll ,-+!ni$ul!to":

    !he main task o" setll =; manipulator is to ll the e%tra spaces le"t in the output

    o" setw=;manipulator with characters.

    E6!$le: 1.coutOOsetll=Q; Out$ut:

    7.coutOOsetw =#;OO 10L QQQ10QQ7#)

    H.coutOOsetw =#;OO

    7#)OOendlL

    ,- !ni$ul!to":

    !here are two important parameter setiosKags =; takes. !hey are iosAAshowpos and iosAAshowpoint.

    hen iosAAshowpos is passed as parameter to setiosKags =; than a positive sign is pre%ed to

    the#etio#!*#output.

    E6!$leA 1. coutOOsetiosKags=iosAAshowpos; OO 70L Out$ut: >70hen iosAAshowpoint is passed as a parameter than it "ollows the setprecision parameter=;.

    E6!$leA 1. coutOO setprecision=H;LOut$ut:

    7. coutOO1.) OOendlL 1.)

    H.coutOOsetiosKags=iosAAshowpoint; 1.)00

    4. coutOO1.)OOendlL"e#etio#!*# ,- !ni$ul!to":

  • 8/10/2019 Cpp Study Notes-libre

    19/108

    !his manipulator cancels the setiosKags parameter. !his manipulator resets again tosetiosKags =; manipulator.

    E6!$le: 1. coutOO setprecision =H;OO1.)OOsetiosKags=iosAAshowpoint;OO1.)OOendlL7. coutOOresetiosKags=iosAAshowpoint;OO1.)OOendlL

    Out$ut: 1.)1.)001.)

  • 8/10/2019 Cpp Study Notes-libre

    20/108

    12

    U#e

    " (e7ne( !ni$ul!to"#:!he manipulators dened $y the users are called as user denedmanipulators.

    :ynta% A o#t"e! W !ni$ul!to",o#t"e! W out$ut-X

    ??#t!teent#?? "etu"nout$ut

    Y

    Calling the user dened manipulators A'out n!e of the !ni$ul!to" li#t to $"int

    3%ampleA o#t"e! W unit ,o#t"e! W out$ut-X

    out$ut 5in'he#"etu"n out$ut

    Y

    CallingA 'out unit

  • 8/10/2019 Cpp Study Notes-libre

    21/108

    13

    INTRODUCTION TO C++C>> is an o$ect-oriented programming language. 'nitially named C with classes, C>>

    was developed $y Barne :troustrup at !R ! Bell a$oratories in *urray &ill, ew Eersey,2:, in the early eighties. 'n 198H, the name=?C with classes@; was changed to C>>. !he ideao" C>> comes "rom the C increment operator >>, there$y suggesting that C>> is anincremented version o" C.

    C>> is a superset o" C. !he three most important "acilities that C>> adds on to C are

    classes, inheritance, "unction overloading, and operator overloading. !hese "eatures ena$le usto create a$stract data types, inherit properties "rom e%isting data types and supportpolymorphism, thus making C>> a truly o$ect- oriented language.

    !he addition o" new "eatures has trans"ormed C "rom a language that to one thatprovides $ottom-up, o$ect-oriented design.

    A$$li'!tion# of C++:

    C>> is a versatile language "or handling very large programs. 't is suita$le "or virtuallyany programming task including development o" editors, compilers, data$ases,communication systems and any comple% real-li"e application systems.

    :ince C>> allows us to create hierarchy-related o$ects, we can $uild special o$ectoriented li$raries

    which can $e used later $y many programmers.

    hile C>> is a$le to map the real-world pro$lem properly, the C part o" C>> gives thelanguage the a$ility to get close to the machine-level details.

    C>> programs are easily maintaina$le and e%panda$le. hen a new "eature needs to$e implemented, it is very easy to add to the e%isting structure o" an o$ect.

    Si$le C++ P"o*"!:

    S includeOiostreamN DD include header leint main=;T

    coutOO@ C>> is $etter than C.Un@L DD C>> statementreturn 0LV DD end o" e%ample

    P"o*"! 4e!tu"e#:

    ike C, the C>> program is a collection o" "unctions. !he a$ove e%ample contains onlyone "unction, !in,-. 3%ecution $egin at main=;. 3very C>> program must have a !in,-.C>> is a "ree-"orm language,the C>> statements terminate with semicolons.

    Coent#:

    C>> introduces a new comment sym$ol DD =dou$le slash;. comment may startanywhere in the line, and whatever "ollows till the end o" the line is ignored. !here is noclosing sym$ol.

    !he dou$le slash comment is $asically a single line comment. *ulti line comments can$e written "ollowsA

    / this is an e%ample le/ C>> program to illustrate/ some o" its "eature

    !he C comment sym$ol DQ, QD are still valid are more suita$le "or multi line comments.!he "ollowing command is allowed.

    DQ this is an e%ample o" C>> program to illustrates:ome o" its "eatures

    QD

  • 8/10/2019 Cpp Study Notes-libre

    22/108

    1

    !he output statement 'out 5C++ i# /ette" th!n C.

    causes the string in Guotation marks to $e displayed on the screen. !his statement introducestwo new C>> "eatures, 'out and . !he identier cout=pronounced as C out; is apredened o$ect that represents the standard output stream in C>>.

    !he operator OO is called the insertion or put tooperator. 't inserts =or sends; thecontent o" the varia$le on its to the rights o" the o$ect on its le"t =gure;.

    out 44 @=

  • 8/10/2019 Cpp Study Notes-libre

    23/108

  • 8/10/2019 Cpp Study Notes-libre

    24/108

    1.

    Retu"n t3$e of !in,-:

    'n C>> main=; returns an integer type value to the operating system. !here"ore, everymain=; in C>> should end with a return=0; statementL otherwise a warning or error mightoccur. :ince !in,-returns a integer type value, return type "or main=; is e%plicitly speciedas int. the de"ault return type "or all "unctions in C>> is int.

    int main=;TMM

    MMreturn 0LV

    St"u'tu"e of C++ $"o*"!: typical C>> program would contain "our sections as shown in gure. !hese sections

    may $e placed in separate code les and then compiled independently or ointly.

    In'lu(e 7le#

    Cl!## (e'l!"!tion

    Cl!## fun'tion# (e7nition#

    M!in fun'tion $"o*"!

    Fig. :tructure o" C>> program

    TO[ENS!he smallest individual units in a program are known as to$ens#C>> has the "ollowingtokensA

    /eywords

    'dentiers

    Constants

    :trings

    > program is written using these tokens, white spaces and synta% o" the language.

    [e3%o"(#:!he keywords implement specic C>> language "eatures. !hey are e%plicitly reserved

    identiers and cannot $e used as names "or the program varia$les or other user-denedprogram elements.:ome /eywords areA

    auto $reak case catch char class const

    continue de"ault delete do dou$le elseenum

    e%tern Koat "or "riend goto i" inline

    int long new operator private protectedpu$li

    c

    register return short signed sieo" staticstruct

    switch template this throw try typede" unionunsigned virtual void volatile while

    I(enti7e"#:

    denti%ers re"er to the names o" varia$les, "unctions, arrays, classes, etc. created $yprogrammer.

    !he "ollowing rules are common to $oth C and C>>.

  • 8/10/2019 Cpp Study Notes-libre

    25/108

    !he name cannot start with a digit.

    2ppercase and lowercase letters are distinct.

    declared keyword cannot $e used as a varia$le name.

  • 8/10/2019 Cpp Study Notes-libre

    26/108

    1/

    \!"i!/le#:Paria$les are locations in the memory that can hold values. Be"ore assigning any value to avaria$le, it must $e declared. !o use the varia$le number storing an integer value, thevaria$le numbermust $e declared and it should $e o" the type intas "ollowsA

    int num$er

    Con#t!nt#:&onstants re"er to %ed values that do not change during the e%ecution o" a

    program. ike C, C>>support several kinds o" literal constants. !hey include integers,characters, Koating point num$ers and string.

    3%ampleA 17H DD decimal integer 17.H4DD Koating pointinteger

    @ DD string constant DD character constant

    B!#i' D!t! T3$e#:ata types in C>> can $e classied under various categories as shown in Fig.

    C>> ata !ypes

    2ser-dened type Built-in type erived typestructure arrayunion "unctionclass pointerenumeration re"erence

    'nteger !ype Poid Floating type

    int char Koat dou$le

    Figure- &ierarchy o" C>> data types

    ith the e%ception o" void, the $asic data types may have several modiers preceding

    them to serve the needs o" various situations. !he modiers signed, unsigned, long, and shortmay $e applied to character and integer $asic data types. &owever, the modier long mayalso $e applied to dou$le.

    Si8e !n( R!n*e of C++ B!#i' D!t! t3$e#T3$e B3te# R!n*e U#e

    Char 1 -178 to >17) 2sed to store single character

    unsigned char 1 0 to 7## 2sed to store unsigned =positive only;single character

    signed char 1 -178 to >17) 2sed to store signed =$oth positive andnegative; single character

    'nt 7

    -H7,)(8 to > H7,)() =-71#to

    71#-1; 2sed to store integer =whole num$ers;values

    unsigned int 7 0 to (#,#H# 2sed to store unsigned integer =positivewhole num$ers; values

  • 8/10/2019 Cpp Study Notes-libre

    27/108

    signed int 7

    -H7,)(8 to > H7,)() =-71#to

    71#-1; 2sed to store signed integer =wholenum$ers $oth positive and negative;values

  • 8/10/2019 Cpp Study Notes-libre

    28/108

    1

    short int 7

    -H7,)(8 to > H7,)() =-71#to

    71#-1;2sed to store short integer =wholenum$ers;values

    unsigned shortint 7 0 to (#,#H# 2sed to store unsigned short integer

    =positive whole num$ers; values

    signed short int 7-H7,)(8 to > H7,)() =-7

    1#

    to71#-1;

    2sed to store signed short integer=wholenum$ers $oth positive and negative;values

    long int 4-7,14),48H,(48 to>7,14),48H,(4)

    2sed to store long integer =wholenum$ers;values

    signed long int 4-7,14),48H,(48 to>7,14),48H,(4) 2sed to store unsigned long integer

    =positive whole num$ers; values

    unsigned long int 4 0 to 4,794,9(),79#

    2sed to store signed long integer

    =wholenum$ers $oth positive and negative;values

    Float 4 H.43-H8 to H.43>H82sed to store num$ers with decimalpoint

    with single precision.

    ou$le 8 1.)3-H08 to 1.)3>H08 2sed to store num$ers with decimalpoint

    with dou$le precision.

    long dou$le 10 H.43-49H7 to 1.13>49H72sed to store num$ers with decimalpoint

    with more than dou$le precision.

    \oi(:!he normal use o" void is

    =1;!o speci"y the return type o" a "unction when it is not returning any value and=7;!o indicate an empty argument list to a "unction.

    3%ampleA

    U#e"]De7ne( D!t! T3$e#:

    St"u'tu"e# !n( Cl!##e#:

    1. struct !o store #t"u'tu"e7. union !o storeunion

    C>> also permits us to dene another user-dened data type known as 'l!##whichcan $e used, ust like any other $asic data type, to declare varia$les. !he class varia$les areknown as o/e't#.

    Enue"!te( D!t! T3$e:

    n enumerated data type is another user-dened type which provides a way "orattaching names to num$ers, there$y increasing comprehensi$ility o" the code. !he enukeyword automatically enumerates a list o" words $y assigning them values 0,1,7 and so on.

    !he synta% o" an enustatement is similar to that o" the #t"u'tstatement.

    3%A enumshape T circle, sGuare,triangle VL

    enum color T red, green, $lue,yellow VL

    By de"ault, the enumerators are assigned integer values starting with 0 "or the rstenumerator, 1 "or the second, and so on.For e%ample,

    voi( fun't1,voi(-

  • 8/10/2019 Cpp Study Notes-libre

    29/108

    enum colorTred, $lueW4,greenW8VL enumcolorTredW#, $lue, greenVL

    are valid denitions. 'n rst case, "e(is 0 $y de"ault. 'n the second case, /lueis ( and *"eenis ).

    De"ive( D!t! T3$e#:A""!3#:

    n arrayis a group o" like-typed varia$les that are re"erred to $y a common name. !hecompiler will allow declaring the array sie as the e%act length o" the string constant.

    3% A char stringYHZW @%y@L is valid in C.'t assumes that the programmer to leave out the null character U0 in the

    denition. But in C>>, the sie should $e one larger than the num$er o"characters in the string.

    char stringY4ZW @%y@L

  • 8/10/2019 Cpp Study Notes-libre

    30/108

    1

    4un'tion#:

    't is a su$program to reduce the sie o" the program and to use di6erent places in aprogram "or more than one time.

    Pointe"#:ointers are declared and initialied as in C. For e%ample

    int QaL it is an int pointer.a W R%L it is an address o" % assigned to a.

    C>> adds the concept o" constant pointerandpointerto a constant#char Qconst ptW@so"t@L it is anconstant pointer.

    S3/oli' Con#t!nt#:!her

    e

    are two ways o" creating sym$olic constants in C>>.2sing the Gualier 'on#t.ening a set o" integer constants using enu+keyword.

    ny value declared as 'on#tcannot $e modied $y the program in any way. 't allows us tocreate typed constants instead o" having to use Sdene to create constants that have no typein"ormation. s with lon*and #ho"t9we can use the 'on#tmodier alone, it de"aults to int.For e%ample,

    !o declare 'on#taW10L =it means const intaW10;. nother method o" naming integer constants is as"ollowsA

    enumT%,y,VL

    !his denes %,y and as integer constants with values 0,1,7 respectively. !his is eGuivalent toconst %W0L const yW1L const W7L

    e can also assign values to %,y and e%plicitly.enumT%W100,yW700,WH00VL

    T3$e Co$!ti/ilit3:C>> denes int9 #ho"t int9 lon* intas three di6erent types. !hey must $e cast when

    their values are assigned to one another. :imilarly, un#i*ne( 'h!"9 'h!"9and #i*ne( 'h!"are considered as di6erent types.

    To use the#i8eof9 #i8eof,K6@- it will $e eGuals to#i8eof,'h!"- and print the sie o"character type

    data

    De'l!"!tion of \!"i!/le#:'n C, all varia$les must $e declared they are used in e%ecuta$le statements. C>>

    allows the declaration o" a varia$le any where in the scope. !his means that a varia$le can $e

    declared right at the place o" its rst use.3%ampleL

    int main=;T

    Koat %L DDdeclarationKoat sum W 0L"or=int iW1LiO#Li>>; DDdeclarationT

    cinNN%LsumWsum>%L

    VKoat averageL DDdeclaration

    averageWsumDiLcoutOOaverageL

  • 8/10/2019 Cpp Study Notes-libre

    31/108

    return 0LV

  • 8/10/2019 Cpp Study Notes-libre

    32/108

    1

    D3n!i' Initi!li8!tion \!"i!/le#:C>>, permits initialiation o" the varia$le at run time. this is re"erred to as dynamicinitialization.3%ampleA No"!l (e'l!"!tion D3n!i' De'l!"!tion

    MM. MMMM. MMint nL int nWstrlen=string;L

    nWstrlen=string;L MMKoat areaL MM.

    areaWH.141#9QradQradLKoatareaWH.141#9QradQradL

    ynamic initialiation is e%tensively used in o$ect-oriented programming. e can createe%actly the type o" o$ect needed, using in"ormation that is known only at the run time.

    Refe"en'e \!"i!/le#:C>> introduces a new kind o" varia$le known as the reference variable. re"erencevaria$le provides an alias (alternati'e name"or a previously dened varia$le. For e%ample, i"we make the varia$le#uare"erence to the varia$le tot!l, then #uand tot!lcan $e used

    interchangea$ly to represent that varia$le.!he re"erence varia$le created as "ollowsA

    (!t!0t3$e W "efe"en'e0n!eFv!"i!/le0n!e

    C>> assigns additional meaning to the sym$ol W. &ere, Wis not an address operator. !henotation o!t W

    means re"erence to Ro!t.3%ample,

    int nY10ZLint R % W nY10ZL DD % is alias "or nY10Z

    char R a WUnLDD initialie re"erence to aliteral

    the varia$le 6is an alternative to the array element n1H. !he varia$le !is initialied to thenewline constant.

    !he "ollowing re"erence are also allowed

    i. int %L ii. int RnW#0L int QpWR%L

    int RmWQpL

    the rst set o" declarations causes to re"er to 6which is pointed to $y the pointer p and thestatement in ii. Creates an into$ect with value #0 and name n.

    maor application o" re"erence varia$les is in passing arguments to "unctions. Consider the"ollowingA

    voi( "=int R%;T% W%>10LVint main=;T

    intmW10L"=m;L------------V

    DD uses re"erence int m W 10 m

    DD % is incrementedL so alsom

    onelocation10

    two names

    call

    DD "unction call "=m; %

    int R % WmL

  • 8/10/2019 Cpp Study Notes-libre

    33/108

    when the "unction is call f,-is e%ecuted, the "ollowinginitialiation occursA int W6 F

    such "unction calls are known as call by reference!:ince the varia$le 6and are aliases,when the "unction increments 6, is also incremented. !he value o" m $ecomes 70 a"ter the"unction is e%ecuted.

  • 8/10/2019 Cpp Study Notes-libre

    34/108

    20

    O$e"!to"#:C>> has a rich set o" operators. ll operators in C are valid in C>> also.

    a? Assignment Operators b? Arithmetic Operatorsc? Belational Operators d? Cogical Operatorsd? )it 7ise Operators e? ncrement6%ecrement operators(? "hortcut Operators g? onditional Operatorsh? "pecial operators

    A##i*nent o$e"!to"#:!he assignment operator is used to store the constants, varia$les, and result o" ane%pression and return value o" a "unction "rom right side into varia$le placed in le"t side.

    > language are A +9 )9 ++9 ) )9 _.In'"eent?De'"eent o$e"!to"#:

    !he 'ncrement operators ++increase the value o" operand $y one.!he ecrement operators 00decrease the value o" operand $y one.3% A i++9 ++i9 i009 00i.

    Sho"t'ut !##i*nent o$e"!to"#:hen same varia$le is used in $oth le"t and right side o" an arithmetic e%pression, wecan use the

    shortcut assignment operators .

    !he operators are A +F9 ) F9 F9 ?F9 ^F 3% A ! +F /9 ! )F/9 !F/9 !?F/9 !^F/Si8eof !n( Co! o$e"!to"#:

    !he #i8eofoperator returns the memory sie occupied $y an operand in terms o" $ytes.

    3% A ! F#i8eof,int-L!he 'o!operator =9;adoins severale%pressions. 3% A 6 F ,3 F 9 3 + 1-

    Con(ition!l o$e"!to"#:

    !he `:are conditional operators. !hey do the o$ done $y i"..else control structure.:ynta% A e6$"e##ion1 ` e6$"e##ion& :

    e6$"e##ion

    3% A /i* F ,!/- ` ! :

    /Rel!tion!l o$e"!to"#:!he operators that do relationship tests with the operands are called relationaloperators.

    !he relational operators areA

    E6 : if,!/- =less than;

    F =less than or eGual to; E6 :

    if,!BF/-

    =greater than; E6 : if,!/-F =greater than or eGual

    to;

    E6 :

    if,!AF/-

    FF =is eGual to; E6 :

    if,!FF/-

    _F =not eGual to; E6 : if,!_

    F/-

  • 8/10/2019 Cpp Study Notes-libre

    35/108

    o*i'!l o$e"!to"#:ogical operators are used when more than one relationship should $e considered inevaluation.

    't gives either !rue value or Falsevalue.

    operator A WWAND

    E6: if,,!/- WW,!'-- !ruth ta$le "or ,

  • 8/10/2019 Cpp Study Notes-libre

    36/108

    21

    Bit0%i#e o$e"!to"#

    !he $it wise logical operators work with those decimal num$ers in its $inary "orm. !he$it wise

  • 8/10/2019 Cpp Study Notes-libre

    37/108

    Block7 is contained in Block1. ote that a declaration in an inner $lock hides adeclaration o" the same varia$le in an outer $lock and there"ore, each declaration o" 6causesit to re"er to a di6erent data o$ect.

    'n C, the glo$al version o" a varia$le cannot $e accessed "rom within the inner $lock.C>> resolves this pro$lem $y introducing a new operator :: called the scope resolutionoperator.

  • 8/10/2019 Cpp Study Notes-libre

    38/108

    22

    !his can $e used to uncover a hidden varia$le. 't take the "ollowing "orm

    :: v!"i!/le0n!e

    !his operator allows access to the glo$al version o" varia$le. AAcount means the glo$alversion o" the varia$le count.3%ample1ASinclude OiostreamN coutOO@ we are in inner $lock Un@LintW10L DDglo$al m coutOO@k W@OO/OO@Un@Lint main=; coutOO@m W@OOmOO@Un@L

    T coutOO@AAm W@OOAAmOO@Un@LintW70L DD m redeclared, local to main V

    Tint k W mL

    coutOO@Un we are in outer $lockUn@;L

    coutOO@mW@OOmOO@Un@VLint W H0L DDm declared again coutOO@AAmW@OOAAmOO@Un@VL

    DD local to inner $lockreturn 0L

    V

    > support these "unctions, it also denes two unaryoperators ne%and (eletethat per"orm the task o" allocating and "reeing the memory in a$etter and easier work. !hese operators manipulate memory on "ree storeL they are alsoknown as free storeoperators.

    n o$ect can $e created $y using ne%, and destroyed $y using (elete. !he ne%operator can $e used to create o$ects o" any type. 't take the "ollowing general "orm

    pointer-varia$le W ne%data-typeL

    &ere,pointer-variableis a pointer o" type data-type. !he ne%operator allocates su5cient

    memory to hold a data o$ect o" data-type and returns the address o" the o$ect. !hepointer-variable holds the address o" the memory space allocated. !he declaration o"pointer and their assignments as "ollows.

    int $ Fne% into!t F ne%o!t

    hen a data o$ect is no longer needed, it is destroyed to release the memory space reuse.!he general "orm o" its use is

    (elete pointer-varai$leLthepointer-variableis the pointer that points to a data o$ect created with ne%. 3%ample

    (elete$(elete

    !he ne%operator o6ers the "ollowing advantagesA1.'t automatically computes the sie o" the data o$ect. e need not use the operator #i8eof.

  • 8/10/2019 Cpp Study Notes-libre

    39/108

    7.'t automatically returns the correct pointer type, so that there is no need to use a type cast.H.'t is possi$le to initialie the o$ect while creating the memory space.4.ike any other operator, ne%and (eletecan $e overloaded.

  • 8/10/2019 Cpp Study Notes-libre

    40/108

    23

    M!ni$ul!to"#:

    *anipulators are operators that are used to "ormat the data display. !he mostcommonly used manipulators are en(land #et%.

    !he en(lmanipulator, when used in an output statement, causes a line"eed to $einserted. 't has the same e6ect as using the newline character ?Un@. "or e%ample, thestatement

  • 8/10/2019 Cpp Study Notes-libre

    41/108

    pWintQ=G;L is illegal. 'n :uch cases, we must use C type notation.

    pW=intQ;GL alterativley, we can use typede" to create an identier o" the reGuired typeand use it in the "unctional notation.

    typede" int Qint[ptpWint[pt=G;

  • 8/10/2019 Cpp Study Notes-libre

    42/108

    2

    E6$"e##ion# !n( thei" t3$e#:n e%pression is a com$ination o" operators, constants and varia$les arranged as per therules o" the language. 3%pressions consist o" one or more operands, and ero or moreoperators to produce a value.

    3%pressions may $e o" the "ollowing seven typesAConstant e%pression

    'ntegral e%pression Float e%pression

    ointer e%pression +elational e%pression ogical e%pression Bitwise e%pression

    n e%pression may also use com$inations o" the a$ove e%pressions. :uch e%pressions areknown as compound e%pressions

    Con#t!nt E6$"e##ion:

    Constant e%pression consists o" only constant values.3%amplesA 1# 70 > # D 7.0

    Inte*"!l E6$"e##ion#:

    'ntegral e%pressions are those which produce integer results a"ter implementing all theautomatic and e%plicit type conversions. 3%amplesA

    m

    m Q n -# m Q%# > int=7.0;

    where and nare integer varia$les.

    4lo!t E6$"e##ion#:

    Float e%pressions are those which, a"ter all conversions, produce Koating pointresults. 3%amplesA % > y% Q y D 10# > Koat=10;10.)#

    where 6and 3are Koating-point varia$les.

    Pointe" E6$"e##ion#:

    ointer e%pressions produce address values.e%amplesA Rm

    ptrptr>1?%y@

    where is a varia$le and $t"is a pointer.

    Rel!tion!l E6$"e##ion#:

    +elational e%pressions yield results o" type /oolwhich takes a value t"ueorf!l#e. 3%amplesA % OW ya > $ WW c> d m > nN 100

    when arithmetic e%pressions are used on either side o" a relational operator, they will $e

    evaluated rst and then results compared. +elational e%pressions are also known as "oolean'#pressions.

    o*i'!l E6$"e##ion#:

    ogical e%pression com$ine two or more relational e%pressions and produces /ooltyperesults. 3%amplesA a N $ RR % WW 10L

  • 8/10/2019 Cpp Study Notes-libre

    43/108

    % WW 10 \\ y WW #

  • 8/10/2019 Cpp Study Notes-libre

    44/108

    2.

    Bit%i#e E6$"e##ion#:

    Bitwise e%pressions are used to manipulate data at $it level. !hey are $asically used "ortesting or shi"ting $its. 3%amplesA

    %OOH DDshi"t three $it position to le"tyNN1 DDshi"t one $it position to right

    shi"t operators are o"ten used "or multiplication and division $y powers o" two.S$e'i!l A##i*nent E6$"e##ion#Ch!ine( A##i*nent

    % W = y W 10 ;L or % W y W 10LFirst 10 assigned to y and then to %. chained assignment cannot $e used to initialie varia$les at the time o" declaration.

    E/e((e( A##i*nent% W =y W #0; > 10.

    =yW#0; is an assignment e%pression known as em$edded assignment. &ere, the value#0 is assigned to y and then the result #0 > 10 W (0 is assigned to %.

    Co$oun( A##i*nent

    C>> supports compound assignment operator which is a com$ination o" the assignmentoperator with a $inary arithmetic operators.

    3%ampleA % W % > 10 may $e written as

    6 +F 1HL!he operator >W is known as compound assignment operator or short-hand assignmentoperator.

    !he general "orm is A v!"i!/le o$ F v!"i!/le &

    OPERATOR PRECEDENCEssociativity denes in the case that there are several operators o" the same priority level-which one must $e evaluated rst, the rightmost one or the le"tmost one.

  • 8/10/2019 Cpp Study Notes-libre

    45/108

    2/

    CONTRO STRUCTURES:

    Control :tructure

    :election :eGuence oop

    i"-else switch do-while while, "or

    !wo way$ranch

    *ulti way

    $ranch 3%it-control3ntry-control

    b

    The if #t!teent : !heif statement is implemented in two "ormsA

    :imple ifstatement ifel#e statement

    a;!he ifstructure tests a condition and trans"ers the control accordingly.S3nt!6 : if,e6$"e##ion-

    X #t!teent# Y3%ample A i"=aN$;

    print"=? is $ig@;Lprint"=?B is $ig@;L

    $; ifel#estructure works according to the true R "alse value generated $y the e%pression.:ynta% A if,'on(ition-

    X #t!teent# Yel#e

    X #t!teent# Y3%ample A if,!"2# F H-

    $"intf,5P!##-el#e

    $"intf,54!il-

    c; Ne#te( if #t"u'tu"e:'" any ifor el#e$lock contains another if9 ifel#e9 el#eif l!((e"then it can$e called as

    Ne#te( ifel#e.

  • 8/10/2019 Cpp Study Notes-libre

    46/108

    2

    fo",iFH i1Hi++- 'outi

    !he while structure is called as entry controlled loop. !he condition is tested rst. '" thecondition satises, the loop $lock is e%ecuted, otherwise the program e%ecution continuesa"ter the while structure. :ynta% A 3%ample A

    (o%hile loo$ #t"u'tu"e:

    YY

    i F 1%hile,i 1H-X 'outini++

    initi!li8!tion

    %hile,'on(ition- X #t!teent#

    in'"eent?(e'"eent

    %hile loo$ #t"u'tu"e:

  • 8/10/2019 Cpp Study Notes-libre

    47/108

    :ynta% Aif,e6$- 3%ample A if,!"2 F H-X X

    if,e6$- if,!"2 F Q-X #t!teent# Y $"intf,5=onou"#-

    el#e el#eX #t!teent# Y $"intf,5I 'l!##-

    Y Yel#e el#eX if,e6$- X if,!"2 F H-

    X #t!teent# Y

    $"intf,5IICl!##J-

    el#e el#eX #t!teent# Y $"intf,54!il-

    Y Y

    S%it'h #t"u'tu"e:#%it'h is called *ulti-directional control structure. !his structure is used when

    decision-making isdepending upon more than two values.:ynta% A #%it'h,e6$- 3%ample A #%it'h,n-

    X X'!#e 1 : '!#e 1 :

    !'tion1 $"intf,5ONE-/"e!2

    '!#e & : '!#e & :!'tion& $"intf,5T

  • 8/10/2019 Cpp Study Notes-libre

    48/108

    2

    Othe" fo"# of fo" loo$ :

    't is possi$le to omit any one o" the sections in "or construct. 'n case, i" we omit, a semi colon

    must $e present.3%amples A a. fo", i1H i++ - $. fo", i1H - c. fo", -e can use more than one initial value, condition and counter inside a "or loop $y using

    comma operator. d. fo",i F19 F1 i9 i++9 ++-

    ARRALSn array is a group o" related data items that share a common name. n array reservescontinuous memory location to place the values consecutively. !he types are A

    1.

  • 8/10/2019 Cpp Study Notes-libre

    49/108

    'nitialiationAt3$e

    !""!3n!+eG#i8e1G#i8e& FX v!lue# Y

    3%ample A int !1H1Hint !1H1H F X 19&99 Y

    Multi0(ien#ion!l !""!3:n array having more than two su$scripts is a multi-dimensional array.

    eclarationAt3$e !""!3n!e#i8e1#i8ei8eN

    'nitialiationAt3$e

    !""!3n!+eG#i8e1G#i8e&G#i8eNFX v!lue#Y

    3%ample A int !&&&int !&&& F X 19&99999Q9 Y

    Pointe" : pointer is a varia$le that contain the address o" any varia$le. 't point to varia$le o" the data type "or

    which it has $een declared. 't is declared with the Q preceding it.

    !he unary operator Wgives the ?address o" a varia$le@. !he indirectionDdere"erence operator gives the ?content o" an o$ect pointed to $y a

    pointer@.

    \!"i!/le \!lue A(("e##

    ]uantity 1 #000

    p .000 #048

    !he value o" the varia$le p is the address o" the varia$le Guantity. ccess the value o" Guantity$y using the value o" p. the varia$le p points to the varia$le Guantity thus p gets the namespointer.

    E6. int $$FWu!ntit3

    assign the address #000 =location o" Guantity; to varia$le p. the R operator remem$ered

    ?address o" ?.

  • 8/10/2019 Cpp Study Notes-libre

    50/108

    2

    4UNCTIONSA fun'tion i# #!i( to /e ! #et of in#t"u'tion# th!t '!n $e"fo" ! #$e'i7' t!#2.

    't will $e reduce thesie o" the program $y calling and using them at di6erent places in theprogram. !he advantages areA Re0u#!/ilit39 o(ul!"it39 ove"!ll $"o*"!in*#i$li'it3. Functions are classied into li$rary "unctionsand user-dened "unctions.

    i/"!"3 4un'tion#: !he "unctions that are already availa$le in the C>> li$rary are calledi$rary "unctions.:ome important categories o" li$rary "unctions are A 'nputD$>cL----------

    V

    4un'tion '!ll :!he process o" calling a "unction "or e%ecution is known as "unction call. nyuser dened"unction can call any other "unction. !here are two types o" "unction callA C!ll /3v!lueand C!ll /3Refe"en'e.

  • 8/10/2019 Cpp Study Notes-libre

    51/108

    30

    !he "unction #u, -can $e invoked in a program as"ollowsA o!t !((v!l F #u,/19%19h1-??fun'tion '!ll

    !he varia$le /1,%1 and h1 are known as the !'tu!l $!"!ete"# =!"*uent#; whichspeci"y the dimensions o" !((v!l.!heir types should match with the types declared in theprototype. !he calling statement should not include type names in the argument list.

    Di;e"ent t3$e# of 4un'tion#

    1. Function %ith $!"!ete"#=arguments;and

    7. Function %ith $!"!ete"#=arguments;and

    %ithout "etu"n v!lue#. %ith ! "etu"n v!lue.

    Sinclude Oiostream.hN Sinclude Oiostream.hN

    Sinclude Oconio.hN Sinclude Oconio.hNvoid main= ; void main= ;T T

    int aW10, $W10L int aW10, $W10Lvoid add=int,int;L int add=int,int;Lclrscr=;L clrscr=;Ladd=a,$;L cout OO add=a,$;L

    getch=;L getch=;LV Vvoid add=int %, int y; int add=int %, int y;T T

    coutOO %>yL return=%>y;LV V

    7. Function %ithout $!"!ete"=argument;and

    7. Function %ithout $!"!ete"=argument;and

    %ith ! "etu"n v!lue. %ithout ! "etu"n v!lue.

    Sinclude Oiostream.hN Sinclude Oiostream.hN

    Sinclude Oconio.hN Sinclude Oconio.hNvoid main= ; void main= ;T T

    int add=;L void add=;Lclrscr=;L clrscr=;Lcout OO add=;L add=;Lgetch=;L getch=;L

    V Vint add=; void add=;T T

    int %W10, yW10L int %W10, yW10Lreturn=%>y;L cout OO =%>y;L

    V V

    P!"!ete" P!##in* in 4un'tion#C!ll B3 \!lue :

    hen a "unction is called $y #u$$l3in* v!lue# !# $!"!ete"# =arguments;, it iscalled C!ll B3 \!lue. !he values placed in the!'tu!l $!"!ete"# !"e 'o$ie( into thefo"!l $!"!ete"#. :o any'h!n*e# !(e to the fo"!l $!"!ete"# (o not !;e't the!'tu!l $!"!ete"#.

    C!ll B3 Refe"en'e:hen we pass $!"!ete"# ,!"*uent#- /3 "efe"en'e, the fo"!l $!"!ete"# in

  • 8/10/2019 Cpp Study Notes-libre

    52/108

    the called "unction /e'oe !li!#e# to the!'tu!l $!"!ete"# in the calling "unction. :o any'h!n*e !(e in the fo"!l $!"!ete"# !;e't the o"i*in!l v!lue.

  • 8/10/2019 Cpp Study Notes-libre

    53/108

    31

    Retu"n B3 Refe"en'e: "unction can also return a re"erence.

    int Wma%=int R%, int Ry;T i"=%Ny;

    return %Lelse

    return yLV

    :ince the return type o" !6, -is int W, the "unction returns re"erence to 6and 3=andnot the value;. !hen "unction call such as !6,!9/- will yield a re"erence to either ! or /depending on their values. !his means that this "unction call can appear on the e"t-hand sideo" an assignment statement. !hat is, the statement

    !6,!9/- F 01

    is legal and assigns -1 to !i" it is larger, otherwise -1 to /.

    Inline 4un'tion:

  • 8/10/2019 Cpp Study Notes-libre

    54/108

    32

  • 8/10/2019 Cpp Study Notes-libre

    55/108

    V

  • 8/10/2019 Cpp Study Notes-libre

    56/108

    33

    ? !/ E6e"'i#e 0& : P"o*"! to i$leent fun'tion ove"lo!(in*9 inlinefun'tion9 (ef!ult !"*uent9 Con#t!nt !"*uent9 C!ll /3 v!lue!n( C!ll /3 "efe"en'e?

    SincludeOiostream.hNSincludeOconio.hN

    int volue=intW;L

    dou$le volue=dou$le,dou$le;L long volue=long,int, int;Linline Koatvolue='on#t KoatW,Koat;L

    int !in,-X

    int !'l"#'",-cout OO ^Function

  • 8/10/2019 Cpp Study Notes-libre

    57/108

    return =l Q $ Q h;LV

    inline Koatvolue='on#t KoatWc,o!t "F1H.H;T

    return =c Q H.14#19 Q r Q r Q r;LV

  • 8/10/2019 Cpp Study Notes-libre

    58/108

    3

    C St"u'tu"e# Revi#ite(:

    structure is a convenient tool "or handling a group o" logically related data item. !heyprovide a method "or packing together data o" di6erent types. 't is a user dened data typewith a templatethat servesto dene its data properties.

    For e%ample, #t"u't studentT

    char nameY70ZLint rollnoLKoat totalmarkL

    VL

    !he keyword #t"u'tdeclares #tu(entas a new data type that can hold three elds o"di6erent data types. !hese elds are known as structure members or elements. !heidentier student, which is re"erred to as structure nameor structure tag, can $e used tocreate varia$les o" type student.

    3%ample #t"u't studentAL DC declaration

    is a varia$le o" type student and has three mem$ers varia$le as dened $y the template.*em$er varia$le can $e accessed using the dotorperiod operatoras "ollowsA

    #t"'$3,A.n!e9

    5Roeve"- A."ollnoF 1& A.tot!l!"2F QV

    S$e'if3in* Cl!##: Class is a way to $ind the data and its associated "unctions together. 't allows the

    data =and "unctions; to $e hidden, i" necessary, "rom e%ternal use. hen dening a class, weare creating a new abstract data type that can $e treated like any other $uilt-in data type.Jenerally, a class specication has twopartsA

    1. Cl!## (e'l!"!tion&. Cl!## fun'tion (e7nition#

    !he class declaration descri$es the type and scope o" its mem$ers. !he class "unctiondenitions descri$e how the class "unctions are implemented.

    Gene"!l fo" of ! 'l!##(e'l!"!tion i#:'l!## class[nameT

    $"iv!te:varia$ledeclarationsL"unctiondeclarationsL

    $u/li':

    varia$ledeclarationsL"unctiondeclarationsL

    VL

    !he 'l!##declaration is similar to a #t"u'tdeclaration. !he keyword 'l!##species,that what "ollows is an a$stract data o" type class+name. !he $ody o" a class is enclosedwithin $races and terminated $y a semicolon. !he class $ody contains the declaration o"varia$les and "unctions. !hese "unctions and varia$les are collectively called class members.

    !hese are usually grouped in two sections, namely, $"iv!te and $u/li'known as visi$ilityla$els and the keywords are "ollowed $y a colon.

    !he class mem$ers that have $een declared as $"iv!tecan accessed only "rom withinthe class, $u/li' mem$ers can $e accessed "rom the outside the class also. !he use o"keyword$"iv!te is optional. Byde"ault, the mem$ers o" a class are $"iv!te. '" $oth la$elsare missing, then, de"ault, the mem$ers are $"iv!te.

  • 8/10/2019 Cpp Study Notes-libre

    59/108

    !he varia$le declared inside the class are known as data membersand the "unctionsare known as member functions. u$lic mem$ers =$oth "unction and data; can $e accessed"rom outside the class. !he $inding o" data and "unctions together into a single class-typevaria$le is re"erred to as encapsulation.

  • 8/10/2019 Cpp Study Notes-libre

    60/108

    3.

    CASS

    rivate area

    o 3ntry toprivate area ata

    X

    Functions

    u$lic area

    3ntry allowedto

    ata

    u$lic areaFunctions

    Data hiding inclasses

    A Si$le Cl!## E6!$le:!he class declaration would look likeA'l!## IteT$"iv!te:

    int num$erL DD varia$le declarationint costL DD private $y de"ault

    $u/li':void getdata =int a, Koat $;L DD "unction declarationvoid putdata=;L DD using prototype

    VLC"e!tin* o/e't#:

    n o$ect in C>> is essentially a $lock o" memory that contains space to store all theinstance varia$les. Creating an o$ect is also re"erred to as instantiatingan o$ect.!o create o$ects o" type ite, use statements such as the "ollowingA

    Ite 6L DDmemory "or % is created

    creates a varia$le 6o" the type ite. 'n C>>, the class varia$les are known as objects.!here"ore, 6is called an o$ect o" type ite. e may also declare more than one o$ect inone statement.

    3%ample A Ite 69 39 8

  • 8/10/2019 Cpp Study Notes-libre

    61/108

    3/

    :imilarly, the statement

    6.$ut(!t!,-would display the values o" data mem$ers.

    Dot O$e"!to":!he dot notation is used to o$tain the value o" the instance varia$les. 't has two parts

    namely the o$ect on the le"t side o" the dot and the varia$le on the right side o" the dot. ote%pressions are evaluated "rom le"t to right. !he general "orm "or accessing instance varia$les

    using the dot operator is given $elowAO/e't"efe"en'e.v!"i!/le n!e

    e can store values into instance varia$les using the dot operator as shown $elowA

    one.c W 10L two.c W 1#L

    e can re"er to values o" instance varia$les using the dot operator asgiven $elowA coutOO ?cW@ OO one.cLcoutOO ?cW@ OO two.cL

    De7nin* Me/e" 4un'tion:*em$er "unction can $e dened as two placesA

    1.

  • 8/10/2019 Cpp Study Notes-libre

    62/108

    *em$er "unctions that are declared inside a class have to $e dened separately outsidethe class. !hey should have a "unction header and a "unction $ody. n important di6erence$etween a mem$er "unction and a normal "unction is that a mem$er "unction incorporates amem$ership identity la$el in the header.

    !he general "orm o" a mem$er "unction denition isA

    retu"n0t3$e 'l!##0n!e :: fun'tion0n!e,!"*uent (e'l!"!tion-X

    fun'tion /o(3Y

    !he mem$ership la$el tells the compiler that the "unction function-name

    $elongsto the class class-name. !hat is, the scope o" the "unction is restricted to the class-namespecied in the header line. !he sym$ol ::is called the scope resolutionoperator.

    For instance, consider the mem$er "unctions *et(!t!,-and $ut(!t!,-as discusseda$ove. !hey may $e coded as "ollowsA

    void iteA A getdata= int a, Koat $ ;

    T num$er W aLcost W $L

    Vvoid iteA A putdata= void;

    T cout OO ?um$er A ? OO num$er OO

    ?Un@L cout OO ?Cost A ? OO cost OO?Un@LV

    Note:!he mem$er "unctions have some special characteristics that are o"ten used in theprogram

    development. !hese characteristics areA

    :everal di6erent classes can use the same "unction name. !he mem$ership la$el willresolve their scope.

    *em$er "unctions can access the private data o" the class. non-mem$er "unctioncannot do so. =&owever, an e%ception to this rule is a friend function;.

    mem$er "unction can call another mem$er "unction directly, without using the dotoperator.

  • 8/10/2019 Cpp Study Notes-libre

    63/108

    3

    In#i(e the 'l!## (e7nition:e can dene a mem$er "unction inside the class denition. hen a "unction is dened

    inside the a class, it is treated as an inline "unction. ormally, only small "unctions are denedinside the class denition. For e%ample the iteclass as "ollowsA

    class iteT int num$erL

    Koat costLpu$licA

    void getdata=int a, Koat $;L DDdeclaration

    voi( $ut(!t!,voi(-?? (e7nition in#i(e the'l!##

    X'outnu/e"n'out'o#tn

    YVL

    Ne#tin* of Me/e" fun'tion# :

    mem$er "unction can $e called $y using its name inside another mem$er "unction o"the same class. !his is known as nesting o" mem$er "unctions.

    P"iv!te Me/e" fun'tion#:'n some situations, we may reGuire certain "unctions to $e hidden "rom outside calls.

    e can place these "unctions in the private section.DQ 3%ample program "or Ne#tin* ofe/e" void sample AA update= ;

    fun'tion !n( $"iv!te e/e"fun'tion. QD T

    Sinclude Oiostream.hN read= ;L

    DD esting o" mem$er

    "unction.

    Sinclude Oconio.hNDD :imple call, o o$ectsused.

    class sample VT void sample AA write=void;

    int mL Tvoid read=void;L DD rivate mem$er cout OO * value is A OO m OO^Un^L

    DD "unction declaration. V$u/li'A void main= ;

    void update= void ;L Tsample:L

    void write= void ;L clrscr=;L

    VL:.read= ;L DD!his "unction call wont work.

    DD

  • 8/10/2019 Cpp Study Notes-libre

    64/108

    $u/li'Avoi(setval=voi(;Lvoi(display=voi(;L

    VL

    !he array varia$le ! declared as a private mem$er o" the class !""!3can $e usedin the mem$er "unctions, like any other varia$le.

  • 8/10/2019 Cpp Study Notes-libre

    65/108

    3

    MEMORL AOCATION 4OR OBJECTS!he mem$er "unctions are created and placed in the memory space only once when

    they are dened as part o" a class specication. :ince all o$ects $elonging to that class usethe same mem$er "unctions, no separate space is allocated "or mem$er "unctions when theo$ects are created.

  • 8/10/2019 Cpp Study Notes-libre

    66/108

    VVL

    int test: :'ountL

  • 8/10/2019 Cpp Study Notes-libre

    67/108

    3

    St!ti' D!t! e/e"#: data mem$er o" a class can $e Gualied as #t!ti'. :tatic varia$les are normally usedto maintain

    value

    s

    common to the entire class. #t!ti'mem$er varia$le has certain specialcharacteristics. !hese areA't is initialied to ero when the rst o$ect o" its class is created. o other initialiation ispermitted.

  • 8/10/2019 Cpp Study Notes-libre

    68/108

    called "unction works directly on the actual o$ect used in the call. !his means that anychanges made to the o$ect inside the "unction will reKect in the actual o$ect.

    4RIENDL 4UNCTIONS:

    The private members of a class cannot be accessed from outside class. In some situations, C++allows a common function to be made friendly with two or more classes, thereby allowing the commonfunction to have access to the private data of these classes. Such a function need not be a member of anyof these classes. The functions that are declared with the keyword friend are known as friendfunctions.

  • 8/10/2019 Cpp Study Notes-libre

    69/108

    0

    .

    "riend "unction have some special characteristicsAIt i# not in the #'o$e of the 'l!## to %hi'h it h!# /een (e'l!"e( !# f"ien(.Sin'e it i# not in the #'o$e of the 'l!##9 it '!nnot /e '!lle( u#in* the o/e'tof th!t 'l!##. It '!n/e invo2e( li2e ! no"!l fun'tion %ithout the hel$ of !n3 o/e't.Unli2e e/e" fun'tion#9 it '!nnot !''e## the e/e" n!e# (i"e'tl3 !n(h!# to u#e !no/e't n!e !n( (ot e/e"#hi$ o$e"!to" %ith e!'h e/e" n!e ,e.*:

    A.6-.It '!n /e (e'l!"e( eithe" in the $u/li' o" $"iv!te $!"t of ! 'l!## %ithout!;e'tin* it# e!nin*.

    U#u!ll39 it h!# the o/e't# !"*uent#.

    !he "unction declaration should $e preceded $y the keyword friend. !he "unction isdened elsewhere in the program like a normal C>> "unction. !he "unction denition does notuse either the keyword friendor the scope operator ::? E6!$le $"o*"! fo" O/e't# !#fun'tion void ma%=X_` m, BC n; DD denition o" "riend

    !"*uent# !n( 4"ien( fun'tion ?DDand

  • 8/10/2019 Cpp Study Notes-libre

    70/108

    'on#t MEMBER 4UNCTIONS'" a mem$er "unction does not alter any data in the class, then we may declare it as a

    'on#tmem$er "unction as "ollowsA

    void mul=int, int; 'on#tLdou$le get[$alance= ;'on#tL

    !he Gualier 'on#tis appended to the "unction prototypes =in $oth declaration anddenition;. !he compiler will generate an error message i" such "unctions try to alter the datavalues.

  • 8/10/2019 Cpp Study Notes-libre

    71/108

    1

    CONSTRUCTORS AND DESTRUCTORSCon#t"u'to" i# ! K#$e'i!l@ e/e" fun'tion %ho#e t!#2 i# to initi!li8e the o/e'tof it@# 'l!##.

    constructoris a special method that creates and initialies an o$ect o" a particular class.'t has the same name as its class and may accept arguments. 'n this respect, it is similar toany other "unction.

    '" you do not e%plicitly declare a constructor "or a class, the C>> compilerautomatically generates a (ef!ult 'on#t"u'to" th!t h!# no !"*uent#.

    constructor is declared and dened as "ollowsADD class with a constructorclass inte*e"T

    int m,nLpu$licA

    inte*e"=void;L DD constructor declaredMM.

    VLinteger A A inte*e"=void; DDconstructor denedT

    mW0L nW0LV

    !he constructor "unctions have some special characteristics, !hese are A

    The3 #houl( /e (e'l!"e( in the $u/li' #e'tion.

    The3 !"e invo2e( !uto!ti'!ll3 %hen the o/e't# !"e '"e!te(.

    The3 (o not h!ve "etu"n v!lue#9 not even voi( !n( the"efo"e9 !n( the3'!nnot "etu"n v!lue#. The3 '!nnot /e inhe"ite(9 thou*h ! (e"ive( 'l!##'!n '!ll the /!#e 'l!## 'on#t"u'to".i2e othe" C++ fun'tion#9 the3 '!n h!ve (ef!ult!"*uent#. Con#t"u'to"# '!nnot /e vi"tu!l.

  • 8/10/2019 Cpp Study Notes-libre

    72/108

    PARAMETERIED CONSTRUCTORS!he constructors that can take arguments are called parameteried constructors. e

    must pass the initial values as arguments to the constructor "unction when an o$ect isdeclared. !his can $e done in twowaysA By calling the constructor

    e%plicitly

    By calling the constructorimplicitly

    E6!$le:

    1. 'nteger int1 W 'nteger=0,100;L DD3%plicit call

    7. 'nteger int1=0,100; DD'mplicit call

    CONSTRUCTOR O\EROADING ,o"- MUTIPE CONSTRUCTORS IN A CASSC>> ermits us to use more than one constructor in the same class. hen more than

    one constructor "unction is dened in a class, we say that the constructor is overloaded.

    CONSTRCTORS

  • 8/10/2019 Cpp Study Notes-libre

    73/108

    2

    DLNAMIC INITIAIATION O4 OBJECTSClass o$ects can $e initialied dynamically too. !hat is to say, the initial value o" an

    o$ect may $e provided during runtime.

    COPL CONSTRUCTOR copy constructor is used to declare and initialie an o$ect "rom another o$ect.

    copy constructor takes a re"erence to an o$ect o" the same class as itsel" as an argument.For e%ample, the statementA

    inte*e" I&,I1-

    would dene the o$ect '7 and at the same time initialie it to thevalues o" '1. nother "orm o" this statement is

    inte*e" I1 F I1!he process o" initialiing through a copy constructor is known as copyinitialiation.

    DLNAMIC CONSTRUCTORllocation o" memory to o$ects at the time o" their construction is known as ynamic

    construction o" o$ects. !he memory is allocated with the help o" the new operator.DQ 3%ample program "or dynamic constructor

    and :tring AA :tring= ;estructor QD T

    Sinclude Oiostream.hN (elete nameLSinclude Ostring.hN V'l!## :tringT void main= ;

    'h!" QnameL Tint lengthL :tring name1=^Pinayaga ;L

    $u/li'A :tring name7=^College ^;L:tring='h!"Qs; name1.display= ;LT name7.display= ;L

    length W strlen=s;L Vname W ne% 'h!"Ylength > 1ZLstrcpy= name, s ;L

    Vvoid display=void;T

    cout OO name OO ^Un^LV:tring= ;L

    VL

    DESTRUCTORS: destructor, as the name implies, is used to destroy the o$ects that have $eencreated $y a constructor. ike a constructor, the destructor is a mem$er "unction whose name

    is the same as the class name $ut is preceded $y a til(e,d-.For e%ample , the destructor"or the class :tring can $e dened as shown $elowA

    dSt"in*, - X Y destructor never takes any argument nor does it return any value. 't will $e invoked

    implicitly $e the compiler upon e%it "rom the program to clean up storage that is no longeraccessi$le. 't is a good practice to declare destructors in a program since it releases memoryspace "or "uture use.

    henever ne%is used to allocate memory in the constructors, we should use (eleteto "ree that memory.

    'on#t OBJECTSe may create and use constant o$ects using 'on#tkeyword $e"ore o$ect declaration.3%ampleA 'on#t *atri% X=m,n;Lny attempt to modi"y the values o" m and n will generate compile-time error.

  • 8/10/2019 Cpp Study Notes-libre

    74/108

    3

    /* Program using class, object, member function,constructors and Destructors for calculating areaand perimeter of a circle */

    #include #include class circle

    {private:

    float radius, area, perimeter;

    public:

    circle() { }//Default constructorcircle(floatr) //Parameterized Constructor{

    radius = r;area = 0;perimeter = 0;

    }

    circle(float a, float p, float r=25)// Constructor with Default Argument

    {

    radius = r;area = a;perimeter=p;

    }

    circle(circle & x)//Copy constructor

    {

    radius = x.radius; area= x.area; perimeter=x.perimeter;

    }

    void read();//Member function1 Declaration// Member function 2 defined inside theclassvoid display()

    {

    cout

  • 8/10/2019 Cpp Study Notes-libre

    75/108

    OPERATOR O\EROADING:!he mechanism o" giving such special meanings to an operator is known as

    operator overloading. e can overload = give additional meaning to; all the C>>operators e%cept the "ollowingA

    The o$e"!to"# th!t '!nnot /eove"lo!(e( !"e: class mem$eraccess operators =., .;

    scope resolution operator=: :;

    sieo" operator=#i8eof; conditional operator=`:;

    !o dene an additional task to an operator, we must speci"y what it means in relation tothe class to which operator is applied. !his is done with the help o" a special "unction, calledoperator function.

    Jeneral "orm o" operator "unction isA.

    "etu"n t3$e 'l!##n!e :: o$e"!to" op,!"*uent li#t-X

    fun'tion /o(3Y

    where return type is the type o" value returned $y the specied operation and opis theoperator $eing overloaded. !he opis preceded $y the keyword o$e"!to". O$e"!to"opis the"unction name.

  • 8/10/2019 Cpp Study Notes-libre

    76/108

    Rule# fo" Ove"lo!(in* o$e"!to"#:

  • 8/10/2019 Cpp Study Notes-libre

    77/108

    .

    E6!$le P"o*"! fo" Un!"3 o$e"!to" ove"lo!(in*DQrogram "or unary operator overloading Y>>, void spaceAAoperator >>=;

    minus=-;Z with mem$er R "riend "unctions. QD T a W >>aLSincludeOiostream.hN $ W >>$LSincludeOconio.hN Vclass space void operator-=space Rs;T int a,$L T s.a W -s.aL

    pu$licA s.$ W -s.$Lvoid input=int,int;L Vvoid display=;L void main=;void operator>>=;L T space :L"riend void operator-=space Rs;L clrscr=;L

    VL :.input=10,-70;Lvoid spaceAAinput=int %,int y; :.display=;LT aW%L >>:L

    $WyL :.display=;LV -:Lvoid spaceAAdisplay=; :.display=;L

    T coutOO^a value is OOaOOendlL getch=;LcoutOO^$ value isA OO$OOendlOO^Un^L V

    V

    E6!$le $"o*"! fo" /in!"3 o$e"!to" ove"lo!(in*Sinclude Oiostream.hN void matri%AAdisplay=matri% *;Sinclude Oconio.hN T "or=int iW0LiOsLi>>;const sW7L Tclass matri% "or=int W0LOsL>>;T T

    int mYsZYsZL coutOOM.iOO^Ut^L

    pu$licA V

    matri%=;T V coutOO^Un^L

    matri%=int %YZYsZ;L Vmatri% operator >=matri% B;L V"riend matri% operator -=matri% , matri%B;Lvoid display=matri% *;L void main=;

    VL Tmatri%AAmatri%=int %YZYsZ; int XYZYsZWT11,17,1H,14VLT "or=int iW0LiOsLi>>; int _YZYsZWT1,7,H,4VL

    "or=int W0LOsL>>; matri% *1=X;LmYiZYZW%YiZYZL matri% *7=_;L

    V matri% *H, *4Lmatri% matri%AAo$e"!to" +,!t"i6 B- *H W *1>*7LT matri% CL *4 W *1-*7L

    "or=int iW0LiOsLi>>; clrscr=;L"or=int W0LOsL>>; coutOO^UnUn *atri% Un^L

    C.i F i +B.i *1.display=*1;L

    return CL coutOO^UnUn *atri% B Un^LV *7.display=*7;L

    matri% o$e"!to" 0,!t"i6 A9 !t"i6 B- coutOO^UnUn *atri% ddition Un^LT matri% CL *H.display=*H;L

    "or=int iW0LiOsLi>>; coutOO^UnUn *atri% :u$traction Un^L"or=int W0LOsL>>; *4.display=*4;L

    C.i F A.i 0 B.i getch=;L

  • 8/10/2019 Cpp Study Notes-libre

    78/108

    return CL VV

  • 8/10/2019 Cpp Study Notes-libre

    79/108

    /

    TLPE CON\ERSIONS:

    3very e%pression has a type that is determined $y the components o" the e%pression.Consider the "ollowing statementA

    int % W #.# D 7 L DD % contains 7, the "raction part is lost.ata can $e lost when it is converted "rom a higher data type to a lower data type.

    C!#t#: e can "orce an e%pression to $e o" a specic type $y using a type cast operator. !hegeneral "ormA

    type-name =e%pression;. DDC>> notationwhere type is a valid data type.

    For e%ample, to make sure that the e%pression %D7 evaluates to type Koat, write

    Koat y W #.# D o!t ,&-

    :ince the user-dened data types are designed $y us to suit our reGuirements, thecompiler does not support automatic type conversions "or such data types.

    !hree types o" situations might arise in the data conversion $etween incompati$le typesA1.Conversion "rom $asic type to class type.7.Conversion "rom class type to $asic type.H.Conversion "rom one class type to another class type.

    T3$e Conve"#ion#

    Conve"#ion "eui"e( Conve"#ion t!2e# $l!'e in

    Basic ClassSou"'e 'l!## De#tin!tion 'l!##ot pplica$le Constructor

    Class Basic Casting

  • 8/10/2019 Cpp Study Notes-libre

    80/108

    { delete name; getch();

    } }

  • 8/10/2019 Cpp Study Notes-libre

    81/108

    IN=ERITANCE

    C>> support the concept o" reusability. !he mechanism o" deriving a new class "roman old one is called inheritance )or derivation*. !he old class is re"erred to as the baseclassor super classand new one is called derived classor sub class.

    4o"# of inhe"it!n'e:1. :ingle 'nheritance = derived class with only one $ase class;.7. *ultiple inheritance = derived class with several $ase classes;.H. &ierarchical inheritance =

  • 8/10/2019 Cpp Study Notes-libre

    82/108

  • 8/10/2019 Cpp Study Notes-libre

    83/108

    public

  • 8/10/2019 Cpp Study Notes-libre

    84/108

    P"iv!te:!he private mem$ers o" a class can $e accessed only $y the mem$er "unctions o"that class.

    P"ote'te(:!he protected mem$ers o" a class can $e accessed only $y the mem$er "unctionso" that class,and the mem$er "unctions o" the classes derived "rom it.

    Pu/li':!he pu$lic mem$ers o" a class can $e accessed anywhere in the application.

    SINGE IN=ERITANCEA

    derived class with only one $ase class.

    )

    DQ a$ 4=a;A 3%ample rogram using class derived A pu$lic $ase

    :ingle 'nheritance QD T int yLpu$licA

    Sinclude Oiostream.hN void sety=int n;Sinclude Oconio.hN T

    y W nLclass $ase VT int %L void showy = ;pu$licA T

    void set%=int n; coutOO^_ W OOyOO^Un^LT V

    % W nL VLV void main=;void show% = ; TT derived L

    coutOO^X W OO%OO^Un^L .set%=10;LV .sety=70;L

    VL clrscr=;L

    coutOO^:ingle 'nheritance program Un^L.show%=;L.showy=;Lgetch=;L

    V

    MUTIE\E IN=ERITANCE: class is derived "rom another derived class is called multilevel inheritance

    class TM.VL DD $ase class

    class B Apu$lic TM.VL

    DD B derived "rom

    class C Apu$lic CTM.VL

    DD C derived "rom

    B

    Base class Grand fatherA

    Intermediate) Father

  • 8/10/2019 Cpp Study Notes-libre

    85/108

    Base class

    Derived class Child

  • 8/10/2019 Cpp Study Notes-libre

    86/108

    .0

    DQ rogram using *ultilevel 'nheritance QD 'l!## (e"ive(&: $u/li' (e"ive(1Sinclude Oiostream.hN T int LSinclude Oconio.hN pu$lic

    A'l!## /!#e void set=int n;T int %L T W nLpu$licA V

    void set%=int n;T % W nL void show =;V T coutOO^` W OOOO^Un^Lvoid show% =; VT coutOO^X W OO%OO^Un^L VLV

    VL voi(!in,-

    'l!## (e"ive(1: $u/li' /!#e

    T

    (e"ive(&LT int yL .set%=10;Lpu$licA .sety=70;L

    void sety=int n; .set=H0;LT y W nL clrscr=;LV coutOO^*ultilevel 'nheritance

    program Un^L

    void showy =;.show%=;L.showy=;L

    T coutOO^_ W OOyOO^Un^L .show=;LV

    getch=;LVL V

    MUTIPE IN=ERITANCE :Create a new class "rom more than one $ase class is called multiple inheritance.

    )-1 )-2 MM )-n

    %

    *ultiple inheritance

    !he synta% o" a derived class with multiple $ase class A

    'l!## D A visi$lility B-1, visi$ility B-7MT MM

    =Body o" ;

    VL3%ample A

    class A pu$lic *, pu$lic Tpu$licA

    void display=void;L

  • 8/10/2019 Cpp Study Notes-libre

    87/108

  • 8/10/2019 Cpp Study Notes-libre

    88/108

    .1

    DQ a$ 4=$; A rogram using *ultiple'nheritance QD 'l!## (e"ive( : $u/li' /!#e19 $u/li' /!#e&

    Sinclude Oiostream.hN TSinclude Oconio.hN int L'l!## /!#e1 pu$licAT void set=int n;

    int %L Tpu$licA W nL

    void set%=int n; VT void show =;

    % W nL TV coutOO^` W ^OOOO^Un^Lvoid show% =; V

    T VLcoutOO^X W ^OO%OO^Un^L

    =IERARC=ICA IN=ERITANCE:

  • 8/10/2019 Cpp Study Notes-libre

    89/108

    V void main=;VL T'l!## /!#e& derived LT .set%=10;L

    int yL .sety=70;Lpu$licA .set=H0;L

    void sety=int n; clrscr=;L

    TcoutOO^*ultiple 'nheritance programUn^L

    y W nL.show%=;LV .showy=;L

    void showy =; .show=;LT getch=;L

    coutOO^_ W ^OOyOO^Un^L VV

    VL

    ) %

    =LBRID IN=ERITANCE: Com$ination o" two or more types o" inheritances is called hy$ridinheritance.

    student

    test sports

    result

    *ultilevel, *ultiple inheritance

  • 8/10/2019 Cpp Study Notes-libre

    90/108

    .2

    \IRTUA BASE CASS:!he child has two direct base classes parent1 and parent7 which themselves

    have a common $ase class grandparent. !he child inherits the traits o" grandparent viatwo separate paths. 't can also inherit directly as shown $y the $roken line. !he grandparentis sometimes re"erred to as indirect baseclass.

    grandparent

    Parent1 Parent2

    child

    'nheritance $y the child some pro$lem. ll the pu$lic and protected mem$ers o"grandparent are inherited into child twice, rst via parent1 and again via parent7. !hismeans child have duplicateset o" the mem$ers inherited "rom grandparent.

    Du$li'!tion of inhe"ite( e/e"# (ue to ulti$le $!th# '!n /e !voi(e( /3!2in* the 'oon /!#e 'l!## ,!n'e#to" 'l!##- !# virtual base class %hile(e'l!"in* the (i"e't o" inte"e(i!te /!#e 'l!##e#.

    class DD grandparentTMMMMVLclass B1Avirtual pu$lic DD parent1

    TMMMMVLclass B7 A pu$lic virtual DD parent7TMMMMVLclass C A pu$lic B1, pu$lic B7 DD childT

    MM DD only one copy o" M... DD will $e inheritedVL

    hen a class is made a virtual$ase class, c>> takes necessary care to see that onlyone copy o" that class is inherited, regardless o" how many inheritance paths e%ist $etweenthe virtual $ase class and a derived class.

    ABSTRACT CASS:n a$stract class is one that is not used to create o$ects. n a$stract class is designed

    only to act as a $ase class to $e inherited $y other classes. 't is a design concept in programdevelopment and provides a $ase upon which other classes may $e $uilt. =3%ampleA Class

    /!#ein *ultilevel 'nheritance program;

  • 8/10/2019 Cpp Study Notes-libre

    91/108

  • 8/10/2019 Cpp Study Notes-libre

    92/108

    V

  • 8/10/2019 Cpp Study Notes-libre

    93/108

    .

    CONSTRUCTORS IN DERI\ED CASS:!he constructor o" the derived class receives the entire list o" values as its arguments

    and passes them on to the $ase constructors in the order in which they are declared in thederived class. !he $ase constructors are called and e%ecuted $e"ore e%ecuting the statementsin the $ody o" the derived constructor. !he general "orm o" dening a derived constructor is A

    erived-constructor = rglist1, rglist7M. grlist,rglist=;;

    $ase1=agrlist1;,$ase7=agrlist7;,

    MM.argument "or$ase=;

    $ase=agrlist;,T

    $ody o" derived constructor

    V

    DQ 3%ample program "or Constructors inerived classes QD

    SincludeOiostream.hN

    SincludeOconio.hN 'l!## oneT

    protectedAint

    aLpu$licA

    one=int %;T

    aW%LVvoid show= ;T

    coutOO^Un a value is A^OOaOOendlL

    VVL'l!## t%oT

    protectedAKoat$L

    pu$licAtwo=Koat y;T

    $WyLVvoid show1= ;

    T coutOO^Un $ vlaue is A^OO$OOendlL

    VVL

  • 8/10/2019 Cpp Study Notes-libre

    94/108

    'l!## th"ee : $u/li' one9 $u/li' t%oT

    protectedAintc,dL

    pu$licAth"ee,int 69o!t 39int 29int

    $-:one,6-9t%o,3-X'F2(F$Y

    void show7= ;T

    coutOO^Un c vlaue is A^OOcOOendlL coutOO^Un dvlaue is A ^OOdOOendlLV

    VL

    void main=;T

    th"ee T,9 .H91H9 &H- clrscr= ;L

    !.show= ;L!.show1= ;L

    !.show7= ;Lgetch=;L

    V

  • 8/10/2019 Cpp Study Notes-libre

    95/108

    ..

    POINTERS9 \IRTUA 4UNCTIONS AND POLMORP=ISM

    Pol3o"$hi# #i$le e!n# one n!e h!vin* ulti$le fo"#.

    !here are two types o" polymorphism, namely, 'o$ile tie $ol3o"$hi# !n( "untie$ol3o"$hi#.

    4un'tion# and o$e"!to"# ove"lo!(in* are e%amples o" 'o$ile tie$ol3o"$hi#. !he overloaded mem$er "unctions are selected "or invoking $ymatching arguments $oth type and num$er at the compile time. 't means that ano$ect is $ound to its "unction call at compile time.Thi# i# '!lle( e!"l3 o" #t!ti' /in(in* o" #t!ti' lin2in*.

    'n "un tie $ol3o"$hi#, an appropriate mem$er "unction is selected with the helpo" virtual "unctions while the program is running. It i# '!lle( l!te o" (3n!i'/in(in*$ecause theappropriate "unction is selected dynamically at run time. ynamic $iding reGuires use o" pointers to

    o$ects.POLMORP=ISM

    POINTERS pointer is a varia$le that stores the memory address o" another varia$le.

    A(v!nt!*e# of u#in* $ointe"#:

    pointers allow direct access to individual $ytes in the memory. !hus, data in memoryisaccessed "aster than through ordinary varia$les. !his speeds up the e%ecution o"programs. ointers allow direct access to output devices, like the monitor. !hisspeeds up programs that

    are graphics intensive.

    ointers allow the program to allocate memory dynamically, only when reGuired,with the help o" the new operator. !hey also allow the program to "ree the memorywhen it is no longer reGuired. !his is done with the help o" the delete operator.

    A Pointe" \!"i!/le:3very $yte in memory is given uniGue address =location num$er; $y the operating

    system. !he name o" the varia$le is the location name given to the $yte=s;, in the program.!he address o" a varia$le is the location num$er o" the rst $yte occupied $y the varia$le.!his address can never $e negative and is usually a very large num$er.

    Pointe" to O/e't#: pointer can point to an o$ect created $y a class.

  • 8/10/2019 Cpp Study Notes-libre

    96/108

    ./

    %.get= ;L%.show=;L

    are eGuivalent to

    ptr-Nget= ;Lptr-Nshow=;L

    since $t"is an alias o" 6, we can also use the "ollowing methodA

    =Qptr;.show= ;Lthe parentheses are necessary $ecause the dot operator has higher precedence than theindirection operator,#

    item Qptr W ne%itemL

    !his statement allocates enough memory "or the data mem$ers in the o$ect structure andassigns the address o" the memory space to $t". !hen $t" can $e used to re"er to themem$ers as shown $elowA

    ptr-Nshow= ;L

    A""!3 of $ointe"# to o/e't#:e can create array o" o$ects using pointers.

    class item void main= ;T T

    int codeL item %Lpu$licA item Qptr W new itemY#ZL

    void get= ;??rray o" # pointers to itemo$ects

    T coutOO@3nter code A Un@L "or=int i W 0L iO#Li>>;cin NN codeL T

    V ptr-Nget= ;Lvoid show=; ptr-Nshow= ;L

    T

    coutOO@CodeW@OOcodeOO@U

    n@L V VVL V

    Thi# Pointe":

    thi#pointer re"ers to an o/e't th!t 'u""entl3 invo2e#a mem$er "unction. Fore%ample, the "unction call !.#ho%, -will set the pointer thi#@ to the !(("e## of theo/e't !.3%ample A class one

    Tint aL

    VL

    !he private varia$le a can $e used directly inside a mem$er "unction,like !F1&L e can also use the "ollowing statement to access thevaria$le A thi#0!F1&.hen a $inary operator is overloaded using a mem$er "unction, we pass only one

    argument to the "unction. !he other argument is implicitly passed using the pointer thi#.

  • 8/10/2019 Cpp Study Notes-libre

    97/108

    return%L

    elsereturn QthisL

    V

  • 8/10/2019 Cpp Study Notes-libre

    98/108

    .

    \i"tu!l 4un'tion#Pirtual "unctions are used to achieve run time polymorphism. !he "unction in $ase class

    is declared as virtual using the keyword virtualpreceding its normal declaration.

    hen a "unction is made virtual, &//determines which "unction to use at run time$ased on the type o" o$ect pointed to $y the $ase pointer, rather than the type o" the pointer.

    !hus, $y making the $ase pointer to point to di6erent o$ects, we can e%ecute di6erentversions o" the virtual"unction.

    +un time polymorphism is achieved only when a virtual "unction is accessed through a

    pointer to the $ase class.

    Rule# fo" \i"tu!l 4un'tion#:hen virtual "unctions are created "or implementing late $inding, we should o$servesome $asic

    rules that satis"y the compiler reGuirementsA

    !he virtual "unctions must $e mem$ers o" some class.

    !hey cannot $e static mem$ers

    !hey are accessed $y using o$ect pointers

    virtual "unction can $e a "riend o" another class

    virtual "unction in a $ase class must $e dened, even though it may not $e used.

    !he prototype o" the $ase class version o" a virtual "unction and all the derived classversionsmust $e identical. '" two "unctions with the same name have di6erent prototype, C>> considersthem as overloaded "unctions, and the virtual "unction is ignored.e cannot have virtual constructors, $ut we can have virtual destructors.'" a virtual "unction is dened in the $ase class, it need not $e necessarily redenedin the ne%to$ect.

    Pu"e \i"tu!l 4un'tion#:'t is normal practice to declare a "unction virtual inside the $ase class and redene it in

    the derived classes. !he "unction inside the $ase class is seldom used "or per"orming any task.'t only serves as a placeholder. :uch "unctions are called ?do nothing@ "unctions. ?do-nothing@ "unction may $e dened as "ollowsA

    vi"tu!l voi( #et, -FHSu'h fun'tion# !"e '!lle( $u"e vi"tu!l fun'tion.

    class containing pure virtual "unctions cannot $e used to declare any o$ects o" itsown. s stated earlier, such classes are called !/#t"!'t /!#e 'l!##e#. !he main o$ective o"an a$stract $ase class is to provide some traits to the derived classes and to create a $asepointer reGuired "or achieving runtime polymorphism.

  • 8/10/2019 Cpp Study Notes-libre

    99/108

    .

  • 8/10/2019 Cpp Study Notes-libre

    100/108

    f#t"e!A rovides support "or simultaneous input and output operations. Containsopen withde"ault input mode.

  • 8/10/2019 Cpp Study Notes-libre

    101/108

    .

    OPENING AND COSE A 4IEOPENING 4IE USING CONSTRUCTOR

    o"stream fout=results.;L DDoutput onlyi"stream %n=data.;L DDinput only

    OPENING 4IE USING o$en,-

    S3nt!6 : 7le0#t"e!0'l!##stream-object

    E6!$le

    : of#t"e! out%lestream-object.o$en,0%lename- out%le.o$en,5(!t!1-

    ifstream in%le;

    in%le.open(0data1);

    MORE OPEN, - 4IE MODES :!hegeneral "orm o" the "unction o$en, -with two arguments isAstream-object.o$en,0%lename9 o(e-

    !he second argument =called le mode parameter; species the purpose "or which the le isopened.

    4ile o(e $!"!ete" Me!nin*

    iosAAapp ppend to end o" leiosAAate go to end o" le on opening

    iosAA$inary le open in $inary mode

    iosAAin open le "or reading only

    iosAAout open le "or writing only

    iosAAnocreate open "ails i" the le does not e%ist

    iosAAnoreplace open "ails i" the le already e%ist

    iosAAtrunc delete the contents o" the le i" it e%ist

    ll these Kags can $e com$ined using the $itwise operator

  • 8/10/2019 Cpp Study Notes-libre

    102/108

    X e6it,1- Y

    !he eof, - is a mem$er "unction o" io#class. 't returns a non-ero value i" the end-o"-le=EO4; condition is encountered, and a ero, otherwise. !here"ore, the a$ove statementterminates the program on reaching the end o" le.

  • 8/10/2019 Cpp Study Notes-libre

    103/108

    /0POINTERS AND T=EIR MANIPUATION

    3ach le has associated pointers known as 7le $ointe"#.

    1;th $yte in the le

    "out.seekg=m, iosAAcur;L Jo "orward $y m $ytes "rom the current position

    "out.seekg=-m, iosAAcur;L Jo $ackward $y m $ytes "rom the current position

    "out.seekg=-m, iosAAend;L Jo $ackward $y m $ytes "rom the end.

  • 8/10/2019 Cpp Study Notes-libre

    104/108

  • 8/10/2019 Cpp Study Notes-libre

    105/108

  • 8/10/2019 Cpp Study Notes-libre

    106/108

    /2

    3%ample A i"stream inleL elseinle.open=?BC@;L i"= inle.$ad= ; ;while=inle."ail= ;; TT MM MM = report "atal error ;

    = process the le ; VV elsei"= inle.eo"= ; ; T

    T MM inle.clear= ;L DD clear error state= terminate programnormally MM

    ; VV MM

    COMMAND0INE ARGUMENTS

    Co!n( line !"*uent# are optional string arguments that a user can give to aprogram upon e%ecution. !hese arguments are passed $y the operating system to theprogram, and the program can use them as input.

    File names may $e supplied as arguments to the main= ; "unction at the time o"invoking the program. !hese arguments are known as 'o!n(0line !"*uent#.

    !he main= ; "unction may take two arguments as shown $elowA!in , int !"*'9 'h!" !"*v -

    !he rst argument !"*'=known as argument counter; represents the num$er o"arguments in the command line.

    !he second argument !"*v=known an argument vector; is an array o" 'h!"typepointers that points to the command line arguments.

    !he sie o" this array will $e eGual to the value o" argc.

    E6!$le A C N e%am data

    resultsargc W H argvY0Z ---Ne%am argvY1Z---N dataargvY7Z ---Nresults

    DQ a$ # A rogram "or create, read and write in lesQDSinclude Oiostream.hN "or = int i W 0L iO9 L i>>;Sinclude O"stream.hN TSinclude Ostdli$.hN "out OO num$erYiZ OO LSinclude Oconio.hN Vvoid main= int argc, char Q argvY Z ;T "out.close= ;L

    int num$erY9Z WT 11,17,1H,14,1#,1(,1),18,19 VLclrscr= ;L i"stream nLi" = argc W 7; n.open=argvY1Z;LT char chL

    cout OO ^argc W ^ OO argc OO ^Un^Lcout OO 3rror in arguments Un^L while=n.eo"=;WW0;e%it=1;L T

    V n.get=ch;Lo"stream "outL cout OO chL"out.open=argvY1Z;L V

  • 8/10/2019 Cpp Study Notes-libre

    107/108

    i" = "out."ail= ; ;

    T cout OO ^Un Un^Lcout OO Could not open le n.close= ;L

    OO argvY1Z OO Un^L getch= ;Le%it=1;L

    V V

  • 8/10/2019 Cpp Study Notes-libre

    108/108

    /3

    'mportant ]uestions in C>>2nit I '

    1. B!#i' 'on'e$t# of OOPS.&. Benets and pplications 'D< :treams les. 4o"!tte( 'on#ole I?O o$e"!tion# ,O"- io# 'l!## e/e" fun'tion#. M!ni$ul!to"#

    2nit I ''. O$e"!to"# in C++).