Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
20 views84 pages

Document 15

Yvooifguvyvtrrty Hutchinson this to me r 7f 7g7g 7f6f. 7g hi 8h in h in to h this t. Of the 8g g8f7 6 7f 7f 7f 6d

Uploaded by

sushanttandale6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
20 views84 pages

Document 15

Yvooifguvyvtrrty Hutchinson this to me r 7f 7g7g 7f6f. 7g hi 8h in h in to h this t. Of the 8g g8f7 6 7f 7f 7f 6d

Uploaded by

sushanttandale6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 84
Object Oriented Vs Procedure Oriented Programming Table 1.4: Difference between Object Oriented Programming and Procedure Oriented Programming Object Oriented Programming (OOP) Procedure Oriented Programming (POP) | ra Object oriented programming language is object oriented. L Procedural programming languages tend to be action oriented. In OOP, the unit of programming is the class. 2 In procedural programming, unit of programming is the function. OOP programmers concentrate on creating their own user-defined types called classes and components. Each lass contains data as well as the set of functions that manipulate that data. ‘The data components of a class are called data members. The function components of a class are called member functions. The instance of a lass is called an object. 3, In procedural oriented programming programmers concentrate on writing functions. Groups of actions that perform some common task are formed into functions and functions are grouped to form programs. ‘Object Oriented Concepts Through CPP [BBA (CA) - Sem. 1V) a3 Introduction to Css 4, OOP trace on data. 4. POPtrace on procedures. 5. Follow bottom-up program design. approach in 5. Follow top-down approach in program design. 6. Basic building block of OOP is object. Basic building block of POP is function. ‘OOP has access specifiers named Public, Private, and Protected. = POP does not have any access specifiers. Examples of OOP are C++, JAVA, ‘VB.NET, C#.NET. Examples of POP are C, VB, FORTRAN, Pascal. 9. In OOP, importance is given to the data rather than procedures or functions because it works as a real world. 9. In POP, importance is not given to data but to functions as well as sequence of actions tobe done. }. OOP provide Data Hiding so it provides more security. 10. POP does not have any proper way for hiding data so itis less secare. In 00P, overloading is possible in the form of Function Overloading and Operator Overloading. 11. In POP, Overloading is not possible. 12.In OOP, objects can move and communicate with each other through member functions. 12. In POP, data can move freely from function to function in the systei FEATURES OF OOP OOP treats data as a critical element in the program development and does not allow it to flow freely around the system, It ties data more closely to the functions that operate on it and protects it from accidental modification from outside functions. OOP allows decomposition, (breaking into small modules) of a problem into number of entities called objects and then builds data and functions around these objects. Object-1 The organization of data and functions in OOP is shown in Fig. 15. The data of an object can be accessed only by the functions associated with that object. However, functions of one object can access the functions Object-2 Member function F Member function Data and function of other objects. Fig. 1.5: Data and Function Organization in OOP ‘The organization of data and function is payroll system is shown in Fig. In Fig. 1,6, data and function organization is shown with respect to payroll system, We can consider three objects like employee, pay slip and other details. Object-3 Fig.1.6 Organiation of ata and Member Function in Payroll ‘+ ig. 17 shows the important features of OOP 1 also shows various features offered by C++ programming language. From the Fig. 17 we can recognize thatthe feature ersstencels no offered by Co programming language. ‘The wrapping up of data and functions into single unit Le, class i called as ‘encapsulation Data encaprlation i lz known ax dat hiding ‘+The data isnot accesible to the outside word and only thse functions which are wrapped inthe clas can aces it These functions provide the interface between the objects data andthe program. The arebound together. nj red Cnc Tregh (BEACON Som B19 Invent ‘+ They are safe from external interference and misuse. This represents encapsulation (er sea This feature Is not avalable in any conventional procedure oriented rogramming language. For example: The atmosphere encapsulates the earth, skin encapsulates the internal part of body. Data Abetraction: Hh ebjecteclentd programning, each chject wil hie estar terface Uarogh ‘which ican be ued. There ano need t oo nt ite inner deta “+ Sotheueer needs to know th external interfaces only, to make wee of an object. The Internal derals ofthe objects ae hidden which makes thom abstract. This technique ‘orfeatuce of hiding internal detallsin an objets known as Data Abstraction. ‘+ Abstraction i the selective examination of certain aspect of problem. The gos of fraction is to isolate those aspects that ae important for some purpose and Suppress those aspets that are unimpertant. ‘+ Many different abstraction ofthe same thing are possible, depending on the purpose for which they are made, In other words, we ean say that abstraction asthe uet of representing essential fetures vrithost inclading the background. details or ‘explanation: Data abstraction isthe process of defining 2 dat type, often called ‘Abstract Data Type (ADT, together withthe principle of data hiding. ‘+The definion ofan ADT involves specifying the internal representation of the ADTS dats a well asthe functions tobe used by other to manipulate the ADT. ‘tm 00P, classes use the concept of abstraction and are defined a ist of abstract ateributes suchas size, weight and cost and functions to operate these attributes. ‘Classes ae alo bown as ADTS. Inheritance: ‘Thentation of defining anew objectin terms of anol oneis an integral part of OOP. ‘The term Inheritance is used for this concept. Inheritance means one class of objets Ines the data and behaviour from another ease “+ Inheritance imposes «hierarchical relationship among eases in which a cil class Inserts from ts parents. The parent class's known asthe base lass and the child i ‘the derived class The base classi also mown ss Superclse and the derived cass ‘known ae Subeas. ‘+ attates and operations common to group of subclasses are attached tothe superclass and shared by each subclass. Each subclass sat inherit the features of As superciass. A child inherits the property of his father. He can acquit new roperties or modify the inherited one. ‘+ Same way, a new class can drive its properties from another existing class. The ‘erived class inherits all the properties of the base (old) cass. Tis allows the tension and reuse of existing code. This also enables the creation of hierarchy of ‘inset which simulate the cast and eubelas concept of cel weld 4 Polymorphism: tis very sel concept in OOF‘. tn simple erms it means one name, many duties. it provides common interfaces to cary out iia tasks 1m other word, we can say that a common interface created for accessing related ‘objects. In Cro, Its achleved by function overloading operator overloading and “dynamic binding. Forecample: ® a ES -E-S &-4a Ea a = Basically, polymorphism means the quality of having more than one form, In OOP, ‘alymorphism refers tothe fact that a single operation can have different behavior {front ejects tn other words different object react diferent tothe sane message. For example, ‘onalde the operation of dation. For twe numbers the addon should generate ths ‘he operation of aditon is expressed by a singe operator + You can use the ‘aprssion xy to denote the sum of x andy for many diferant typeof x and y Integers, eating pint numbers and complex numbers and even the concatenation cttw sng Similsry supposes numberof geometrical shape all espnd tothe message dae, Each object react to tis teste by dsplayng its shape on 4 dupay screen Cbviowsy the aetal mechanism fr delaying te beter trom one shape to ‘bother butall shapes perform hs takin reponse othe sate message Message Passing: Ie isthe proces of involing an operation oman object. tn response toa messge, the ‘oresponding method (union) executed inthe bj. (oP consist af cbjet and classes Itconsis of eof eject tht communicate with ‘ach ater tie wry necessary fo understand property the cases, objects snd ‘he meseage patsing communication betreen objec. objects communicate wet one anther by sending ad receiving information & tmenage fran objet ea request for execton of precede, and therefore wil Invoke a function Qrocedure inthe een objet tha generates the dese result Message passing involves spciyng the name ofthe objec, the name ofthe function {rnesage) andthe nformaton tobe sent. o Object Oriented Concepts Through CPP [BBA (CA) -Sem. IVJ__1.-11 Introduction to C++ 6. Extensibility: * Itisa feature, which allows the extension of the functionality of the existing software components. In C++, this is achieved through abstract classes and inheritance. 7. Persistence: © The phenomenon where the object (data) outlives the program execution time and exists between executions of a program is known as Persistence. + In C++, this is not supported. However, the user can build it explicitly using file streams in a program. 8. Delegation: * It is an alternative to class inheritance. It is a way of making object composition as powerful as inheritance. In delegation, two objects are involved in handling a request. © In C++, this approach takes a view that an object can be a collection of many objects and the relationship is called has-a relationship or containership. 9. Genericity: * It is a technique for defining software components that have more than one interpretation depending on the data type of parameters. * InC++, genericity is realised through function templates and class templates. ae Tokens | The smallest individual units in a program are known as Tokens. * Atoken isa group of characters that logically belong together. * Token is a sequence of characters from the character set of C+, which is identified by the compiler. * C++ tokens are keywords, literals, identifiers, operators, other symbols (separators) are shown in Fig. 2.1. ‘+ A C++ program or application is written using these tokens, white spaces and the syntax of the language. (2.1) Fig. 2.4: Tokens in C++ E54 identifiers = * An Identifier is any name of variables, functions, classes etc. given by the programmers. © Identifiers are the fundamental requirement of any language. © The identifier isa sequence of characters taken from C++ character set. © ‘Therules for the formation of an identifier are: 1. An identifier can consist of alphabets, digits and/or underscores, 2 An identifier must not start with a digit. It start with an alphabet or underscore(_). 3. Ctt is case sensitive that is uppercase and lowerease letters are considered different from each other. 4, Identifier should not be a reserved word. 5, Identifier contains maximum 32 characters. = Some valid identifiers are: result, x, _nt, acc_no, basicpay ERE] constants = Constant refer to fixed values that the program cannot alter or change * A cconstant is an explicit number or character (such as 4, 0.5, or ‘c’) that does not change. As with variables, every constant has a type. ‘© Anumber which does not change its value during execution of a program is known as constant. © Aconstant in C++ can be of any of the basic data types, const qualifier can be used to declare constant as shown below: const float pi = 3.1415; * The above declaration means that pi is a constant of float types having a value 3.1415, © Examples of valid constant declarations are: const int rate = 50; const float pi = 3.1415; const char ch ti ced on Tah EAC) Sem M22 esi tho ‘The following types of constants are availabe in C+ 1 Integer Constants: Intoger constants are whole number without any fractional part. C++ allows three ‘types of integer constants (@) Decimal integer Constants: It consists of sequence of digits and should not begin with (rs). Forexample,124,-173, +108 (4) Octal integer Constants It consists of sequence of digits starting with O (cr). Forexample, 014,02 (bu) Headectmal mteger Constant 1 consists of sequence of digs preceded by ox 2. character Constants: ‘Accharacter constant In Cts must contain one oF more characters and must be ‘enclosed in singe quotation marks ‘+ For example‘, etc Cex allows nongraple characters wich cannot be typed FEE scope Resolution operator m= The rer opera a dante ayo tn {tse to aces loa aie even Ifthe lal vara hs th same mame as toa + When the tame function name is uted fr many sey, then tis compen i aval by sng cope maison open elie ha de eh Sach fcr set «heparan mettre ide ub + smtae svartable rane ‘Suppose in ac program, there are two variables withthe same name a. Ones global, (outsidea function) and other isica (insides funtion). ‘We atempt to access the variable a in the function, we always access the local, ‘arable (priority toca. Program2.5:Simplescoperetcltionopertor. SSS srt maine) ‘ coutee"\n Local ae*ccace"obal as"ee: 8 coutee"\n Local ae*ccace"obal 64695 + inthe following example, he declaration ofthe varableX hides the dass type, bat you can sil uae the state cass member county qualifying i with the cass {ype andthe scope resolution operator. 11 using nawespace st; clare ® « public: % tn td cana Tag HA CAS) 238 einige 06) a.getaatag auputeatads > output: FEE) serory nanagerent Operator = or dye emery lvestn Cr+ povids new operat. weve male) Tascinc ances tr dmamicaeon «Tor dymaedeaention Crs pve dete) oper, which same a re) Rca 1. ew preter Tier sued fr aloaton memory, Soon nce | este none eee ee ee tee eal sieve sh foe ff etna freee 2. beets oper The dete operator easter res the memory Meted by ome ‘Theptr_var is the pointer toa data object which is created by new. wage det + Wihearay saloaedby ew then ore we ust the ollong seas Seat tee rd + tases notepese tm en ray eet Freamla ede (18 Sa sincecinrem themes he ond cnet TreghEP BAIA -Sem M22 sagen wtces + sfuncion il ely oly to gt aera decimal pin. ececamplesetpecvion@y output: 5. 3. filing umased postions: + linge unused postong othe eld can be done by using set. sett, «ee une enon be led by aing "sen. ses eet C895 owes [3 [e131 213] 4 setae: + inued we show thebare ofa number, for eampe setbae( i) «+ tahows hall number are decal nmber i me. Gee din smn Baan ti ee ph ony wich cm bo ‘manipulated th Fags, se an wrt anton «Tals intone ret eft ns ft hacen stn ost Taps forhecuren steam obe Spat feragy as crags agen 0: «set and unset = + et fant ca se be with ely om apart Argan wilb afb ‘able233 Arguments fos: showase thelps to se base indiestoran output oss uppercase helps to use uppereae letters. Int maint) ‘ nt af] = (35 -2, 82, 15, 28, 995 nt mand (Ant af], Ant 5); /Vorototype: > Ant mach (Ant pls int =) ‘ for (hoashesstee) t 46 (elspa) {nas = plils) > > output: EEE) Return by neference ey ee ren fp ee poe ipataon emery ca « Bimentut titi casmatwaistorais ee Seta ee Se ‘ the object cout. nc Ondo Tg BBA CS 238 sagen wih coutee"inter values for to integers"; inva [tbe Function cals given Zt reference ubich 1s returned 4s assian Large (@) 9) = = 5 > Ant targe (Ant 8p, int 8a) « 16 (we {retura pi) //function returns the value theough reference alse teeta a} » output: Enter values for tro integers 3820 Second munber = 1 1 we executive the progran one sore tine then output will be: fnter values for to integers 83 + when the program gets executed return the reference tthe variable which has the larger vale And ths assigns the value-1t0it EEG. mune runcrions foe ‘Ce inline function Is powerful concept that is commonly used with clases. If 2 ‘ineton is laline, the compler places a copy of the code ofthat function at each point where the function called at compile te, + Any change to an inline funetion could require all clients of the function to be ‘recompile because compiler would need to replace all he code once apain otherwise ‘twa continue with ol functanaity ‘+The advantage of using function isto save the memory space. Consider 2 stuation ‘were seal function i called number of times calling a function requires certain rerheads sch a: Passing the fonction, Passing the values or push arguments int the stack, Savethe registers Return back oclling function, ec ond Cnc HA CPIBEACA Sem) 234 saponin wh co= ‘+ tmnsuch situation (fsmall program called numberof tie) execution time requires more. Fr the above problem, ¢ programming language provides macros. But macros fare called at execution time, 10 ual error checking doce ‘not occur during omplation ‘+ orthe above situation, C++ compiler put the code drecty inside the function body of calling program. Every time when function is called, at each place the actual code from the fonction would be insered, instead of & Jump to the function. Such nline function name (List of argunents) I1tenetion voty > + whan we donot specify Keyword Inline then only ane copy of function code abject ‘ede i ealled depending upon the funtion al This usrated in Fig. 26. =D ED KD GD 1g.246 Calla Giventoa Function + batas we sald above loot tines pede forall tes cls to execute we ake this function Inne then the elling statement is replaced uith the function code. So it ‘minimizes the time spent on jumping. pushing arguments and soon. This is shown in ig 22. ig 2. cal given tine Function Program 2.16: Program llurrates the use of inline function to compute square of @ somber = iincludecsostrean. ty Intine int sq (Int ») ( panes return ps > Ant main) « coutecaquare Ss"cesa(n)ccendly » output: square is 144 (EM veraurrancuments m= ‘+ Cr allows to define an argument whose value wil be automatically used by the compiler, if tis not provided during the funtion eal this argument is led as default arguments. + When declaring a function, we can specify a default value fr each parameter in Co nC the concept of default arguments used, We know that when a function ellis sven the suber of arguments of function definition and function cll should be Same; otherwise, eror willbe displayed But in C++ we ean specify default value for ach parameter when function is declared. + Theparameters which doesnot have any default argument ae placed first whereas ‘those with default values are placed later. Therefore, we can call the same function with fewer arguments than the defined one in prototype. The default altes are Specified when the function is declared. + Compiler takes care ofall the default arguments and values through the prototype. In ‘short wy, this means that when a function wes default argument the actual function cll asthe option to specify new values or us the default values +The default arguments are generally used in the situation where some arguments are daving the same value Program 2.17 rogram shows the use of default argument. Hincludecsoetrean.h> Ane MULECARE 8, Ant Boz, Ant e=3, An A); //prototype ne ming) € ‘coutecnult(2,5) output: ‘+ tn the first al we have specified 2 arguments, hence default value of ¢ and d are {ed In second cal default value disused In3 call cefule vale of, dareused ‘+The default arguments are checked for the type at the time of declaration whereas they are evaloated atthe time of call The default vies are checked from right to Jet Therefore if we have declared the prototype in flowing manner, comple ells {eorheter tis valid or ine + Forexample: Led (ine Sot by srt = 38, Ant g = 40)s vate 2 ad (Ant 2'= 5, Ant by Ant © = 38, Ant d= 40); Salts 3. ed (int a, Snt by Set € = 28, Ant ds Amalie 4. ed (Ant a, int by Sot ey Ant d = 40)3 valid + Itisveryimportanttoroe the two main points about default arguments: 1 Ifwe first declare a function and then define it, make sure to specify the default argument values inthe declaration and tin defiition. 2. Dont specity the default values in the function definition fthey are already specified in function declaration. ‘rogram 2.0: Program which consist a function to find out the rate of Interest with default argument. = ‘include Using maneepace Feds float SiCint py Ant a, Ant mS) Sot eain() ‘ coutecrenter principal anount mp2 tet rtd Cnc Tap PP EAC Sm) 257 sepeingwthcs coutee"enter duration (19 years): *: cima; coutecrEntar rate of interests“ cmitcerStaple interest = *ceah(p, 9, 195 coutee'simple anterest = “C4st(e, mt > output: Enter principal snount: 1080 fnter duration (in years): 2 Sinple interest = 2005imple interest = 100 Program 219: Write a program to calculate area and circumference of a cre ual Inline function. ‘nclusecconto. n> const pi = 3.141595 smtine float cSreun(float x) //Finds circumference of circle ‘ return(2tpten); Instn tone aeaese 99 Iftings are o rele i recunioes ots ming i fat or0; Saeco ner he rl of there * Sen Bente cieoeen - eres: wee Wael nets eens ) output: jot rad ont Tigh CPP BAIA) ‘ har nanel28); pubise: void getaata (vod): ota pueeata (veld); » ose stucent:: getdata(vos) ‘ coutectenter roll:*5 > vote stucent::putdatavota) ‘ foutectnane:"cenanece\8"5 > ne maine) « art ts student [315 /Jareny of hae chose for(tonsteaziee) ‘ Stu eetaatad ) for (ieastcaitee) < sts) pureatagrs return 65 > tpt: 1 Student Inforestion Enter rane: kira bie dnc Teh PAA) 322 cs Vota display 06) x contcctn Rak sera; covtce"n Eng» “Cag , Comex 26m (commex c2) ‘ Gipasl Sptseiet ctnag = ae + Ci retwr(@)s , 11 ed of case im mine) ‘ ert oti, 205 eget ot, 40): 22th. na); coutcct At nts esiepay-ot 3s > output: tals Ei rwenoruncnon _—s3 ‘The functions that are dered wilh the heyword fend ae Frown a fiend factors + To make a0 outside faction endly wo cat we have to spy dear this Tincin a endothe ches Ati cin ict tt ot mambo chm tb aca oh Clete private and potcad merbers, rend fncios are not coniered cat ‘member Cy ar nema eter uncon ates even spec acre pres + lends are not tn the cans acope, and they are not called uring the member scvon operator >) leh remembers anther lee he td Cnc Teg PHAN fm] 328 Ce edocs + Ferecample: c Pious: ‘Fiend void abe(vote)s ‘Te faction declaration in above example shouldbe preceded by the keyword friend, Program to Ada Two Numbers sing Friena Function. sing nmespace Sta dass tow ‘ nt xe Ye 25 pantie ‘ota Spur) « cout <¢ “Enter the value of X and 9: ) ‘friend void ada(tenp 883; vote etspiay() ‘ ) » old add(tenp &¢) etnpsts seat; eaéisplay(): > ‘outpst: Enter the value of x and 9:18 20 hj tad conc Thengh cP BAA) Sem.) Ab enn nd Desc for (int $0 ‘ om. atsp03 bts snerement(); > S504) = output: ZEW] Parameterized Constructor = ‘Sometimes, is essential to intial the various dat elements of different objects ith different values when they are created. This achleved by passing arguments 0 the constructor function when the cbject are created. +The constractors which secapt say number of formal parameters and that formal Parameters are used o initialize the object are called parameterized construtrs + -Aparameteriad constructor defined as “a constructor which accepts one or more arguments/parametes at the time of decaration of object and initales the data ‘members ofthe object with thee parameters/arguments" + Thesyntaxto define a parametrized constructor given blow: class class name(); ‘ public: lass_name()(parant, paran2, .. paraat) « 17vedy of the constructor > » + Ferexample: student: stent (int £) ‘ > tht rte cong eg CP BUA) Sem |_498. + These parameters are passed atthe time of object creation. These parameters can be of any data type except ts own class datatype. The dagrammatie representation i shown in Fig. 3 Program 44: Program for parameterized constructor sing manespace std; class sample 4 private: nt bs sample (Int p) // paraneterized constructor t > void aisp 0 ‘ > » nt rain ‘ sample ob1(15):_// value passed through bject ob.aisp0s » output ‘The output of above program ls 15, The formal parameter value is pused to the ‘constructor where actual parameter gets this formal valve and initialization of objet icone. +The passing of argument canbe dane ellowing wo ways: 4 Calla constructor explicit. 2. calla constructor impli Ant maint) ‘ franple object (10,20); franple dbject2: 11 Constructor invoke. object.visplay0); objecta.oispey0; > output: 1m Constructor ‘+ Ince itis possible to define constructors with default argument. Forexamplecomplestest (Flost real, flost nae = 8): ‘+ Inabove statement default valu ofthe argument imag/= 0, then the statement. comlextest c1(6.8) ‘esigns the value 40 to the rel variable and 00 toimag (by desu) ‘+The default argument is checked for its datatype atthe time ofits declaration and ‘gets evaluated atthe time of call. These arguments ae evaluated from right tet. 1+ Whenever, call is made toa function without specifying an argument, the program wil automatically assign values to the parameter from the default function rototype declaration ‘+ Defaultarguments are useful when user wants same value forthe argument. + Thediagrammatic representation of defvult argument shown in Fig. 6. ‘ig. 446: Contractor with Defalt Argument +_Defauttarguments facilitate easy development and maintenance of program, Program 48: Program to declare as date heling values of day, month and year having constructor funtion to iialize these vals Set value of year = 2009 asa default, value Acceptand display these values of two objects. te rtd ons TraughPBBA CS) enn attr, sing ranespace std; « ine ds mys late (int 61, Sot at, ine yt = 20) yews ? vod display() ‘ cout «6 May = * «6 deena; out » ne maine) « date €1035,22) fate 602012 3)5 ‘tsplay()3 feez.atsplay(): ) output: ‘iy = 35 DYNAMIC INITIALIZATION OF CONSTRUCTOR 1+ Ines cas objects can be initialized dynamically. The inital valve ofan object may beprowided during rin ime +The advantage of dynamic inttalization of abject that we can provide various {nluallzation formats, using overlosded constructors, this providing the NexBilty of Using different format of data at runtime depending upon the situation oF condition. ‘Destructor isa special member function which ls called automatically whenever 8 has object is destroyed. 1+ The primary usage of the destructor function is to release space on the heap. Whenever 2 partial object goer out ofthe scape of is existence, destrtors willbe called automatically an it takes ot the allocated memory. “+ Destructor are invoked by the compiler imply when the termination of programa takes place. Buti ie always better to invoke the destructor explicitly by waiting i into the program code ig. 47: Destrctor 1+ A destructor alia special a thas same name a that ofthe caus of which it 2 ‘ember bat with a= (ie) sign preted toe name and which is wed te destroy the bjcts that have been created by a eantrucor It ets invoked when anabject scope isover. + Syntaxof Destructor: ‘late clare mane « pubtte: class_name): { “elasi_nane()[/heater of the destructor ‘ ‘Povty of the destructor. /data variables aenber functions eetand Vital Base Cle. ‘capabilites the new clases requires ‘+ nberitance i the proces by which one object can acquire the properties of another objet. Inhertances the process of eeating new canes frm an existing clas. ‘+The exiting clase le Known as base clase and the newly rested clas called a8 erived clas. The derived cass inherits all capabilities ofthe base clas. A derived ‘assis more specific than ts base class and represents a smaller group of objects. ‘+ For example, Red Delicious apple is part of the clasiiction apple, which in turn is art of the fruit lass, Hence, inheritance supports the concept of dasifetion; with ‘he help of classification an object need only define thse qualities that make i “unique within its cass. ‘+The inheritance mates it posible for one object tobe a specific instanceof @ more teneral case, Prample of ineritance hierarchy of shape fs shown in Fg. BSS Pees Mig. 5 Shape ero 6 ‘+ Themain advantage of inheritance are 1 Ie helps to implement software reusability. Once the hierarchy is dane, the ‘specific data tothe particular clas can be aed as per the specification ofthe ! access nadifler> cbate 17 boty of cass bic red Congr eg BAAN Som. BM) 532 ce Summary about Access Specfirs: Table $2; Access in a Derived Class Dave ase Derived Cats Public derivation | Private derivation | Protected derivation Private otaccessble | notaccessble | notacceatble Protected protected private protected Pebli public private protected. [TYPES OF INHERITANCE. There are many ways in which we can create derived Gass There are five pet of Inheritance ae flloon: 1 Single inheritance 2. Malllevel inheritance 3 Maltipie inheritance 4 Hierrehiealinhertance and 5 Hybridinheritance ERY single mheritance ‘When one base clas is derived by one child cass, then it ie known as single Inheritance, The existing base clas known as ret base clas whereas, they ney created class called as singly derived elas. Is shown in Fig 56 ig. 34 Single nbertace ‘+ Example: Suppose a college want to store information of undergraduate (UG) and postgraduate students (PG). Both are having registration no, name, and address Each Dostgraduate student also have sdaitional attributes along wit sbove attributes are Dlacement company name. Itean show asin Fig. 57. 757 ject ved Caen Tengh CP BEA) Sem) 533 Program 5.6: Program to usrate single inheritance, ineludectostrese> sing manespace sts ‘ protected Ant reane: char name[ 2015 char aser(30]5 putt wold getéata() { coutecenter registration no, name and address"; ‘hnosregnaronane sar; > vous atspiay() 4 coutec"registration no.e "eerepne: coutee" address « "ecales d Di HTend of base class late Postudent: public student ‘ private: ‘char conpnatel28]3 public void get_p6 data() ‘ extanta(): fouree"\nenter the company mane in>seempna > vote atspr6() t cautee"yn registration no. futec"\n name = oud base: ats90) ‘ outce"Emp no. 1s compo > void derived: get©) ‘ bases: get(: coutcerenter baste salary: Ws > ‘old dortvad:s dtsp0) ‘ bases :d4sp(05 courcerbaste salary = “ecbsalary; > oss maint) ‘ derived ob(20]: Ant 4, coutcc"How nay eoployees?"s for (Set;hensies) ‘ bli Lest; } outcernane empo.sex bsslary \0"; output: How many employees? 2 fencer mane: Prajata Enter employee td: 181 enter name: Praniat fnter employee id: 182 ane expre sex salary ame abe emp no. 6 fort tate salary = 10000 rane sxy2 tmp no. $5 «102 __sexen_taste salary = 40000 EEE] Muttitevel inheritance ‘hen a base clas is derived by a child class which further derived by another child lan then es known as Mulevel Inheritance. ‘+ The clas which provides link between two classes is known as intermediate base ‘las Ths haste in Fig 58 rte 7 0d Som 5.20 Program 5.91 Consider the example of student data, Base class is student. Class test {nermediate base clas and results chilé cas. The clase result inerits the deta of ‘rks obtsned inthe test andthe roll no of student fom base cha rough mulleel fnterttance ‘sing manespace st clase stucent 4 protected: pootte void getCint ») 4 roll = xs > old aispiay() ‘ ? b A protected: Ane markt, mars ‘old geteark(int a, int 8) ‘ sania = ? ‘old atspmark() ‘ couteermar = \w'cenan cena =eenaea: , » lass results public test « Ant totals te rtd en Tag PHBA) Se 8.2 tees void aisplayaln() ‘ aispiay()s aispakOs coutec"totale"ectotals > Ane maine) reget): Fgetmare(6,75); etsolayaliO; > output: ara = 75 EEE) Multiple inheritance When mor noe base cts are inetd dered dy then such pe of Ime eels aps ihetane Rg Soo te epee eee ety) [Ee con «coh ig.5.10- mug inhertane ‘Brampl: Ald ners the features from father and iteligence from mother, Ea EF a is = eS ig 531 mile imbectance pubic: vets stspiay() ‘ cautecta s * cence"\ats par ary aye auteetnty = "ence Ant mainc) ersved 005 ob.get_9(50)5 ob. got (68); ways 10 Program 541: Consider an example to print biodata of a diploma student hhaving personal and academic information. Program to ilusrate use of multiple ‘heritance. a ‘ncludectostream snctadecestring> sing ranespace std; cass personal 17 base elasst ‘ private: char rane (38), ema. s6(50]5 protected oid get personal info ) ‘ couteer\ Enter nase & em Ad oF 3 person = *; tm >nane>venath 16; te red Coen Tm P(A CA -Som. 5.25. vold display_personal_tnfo( ) ‘ coutee"\n Mane = coutee"\n Eas S > Di 11 nd of base e1ass1 laze seacenic ‘ private char tenth class(20];, protected? void get scadente Snfo( ) t 17 base class 2 coutee"\n ten tenth make": > void find_elass( ) ‘ AF (tenth marks70) sereey (tenth class, SF (enth parks) sereay (tenth class, ase SF (tenth markanesoy sereay (tenth class, SF (enh mara) streey (tenth class, Stresy (tenth class, > osetinction"); sraret class"); “rainy: old display acadente fo( ) ‘ coutee"\n Tenth mans = $ind.etass( coutce"\n Tenth class = ‘ ne 15 1 end of base ctass2 jet vented Coca eh CP BEAL fom. 5.26 late bio data: private persona, private aeadente —// Derived class ‘ pubite: wold dtsplay_biodatat 3 void get info 9: 1: 11 end of derived class 11 Nosbor functions of derived clase old bio auta:satepiay btoaaeat ) tsplay_personal_info ): cauteetacadente infow "cen; ‘teplay_acadenic_ info): sta: :get info ) get_personal_infot setncadenle info 32 int ) 1) First read info get infor 3 11 now petnt biodata display biodatat V3 ’ ‘output: Fnter name & eral Ld of @ peson = Prajakta abe@yahoo same = Prajakea nail td = sbcByahoo “Tenth clase = ofsténction te iid Conn Toh FEA) Sam W839 hence ‘oud getsn(int 5) {smart = $3) void dispe() E coutccenarkce"\n"; } ubLie test, public sport void dtsplaytotal() ‘ eispiey0; ispearkOs 859505 coutecrtotal = *cctotals > sing) reget): regetmark(5, 60)5 regeesn(70)3 reatsplaytotal(y; output: ‘otal = 369 MY vinrvas base = ‘Consider situation where multilevel mullple and hierarchical al the threekinds of {hertance are involve. This ustrate in Fig $27 ‘+ tm the Fig. 57, the base das is inherited by both Derived and Derived Deriveds ‘irc inert both Derived and Derived2. All the publican protected members of Base are inherted into Deried® twice through both Derived! and. Derivet2 Therefore, Derived3 would have duplicate sets of members Inherited. This causes ‘maigulty when a member offsel used by Derived it fd cnc Tag CPPHA CA) Sm 537 ht ‘ pub. vote cisptay() t puenunber(s purmarke()s puescore(): outeer\n\eTotal Seare:*cetotals 5 % srt maine) ‘ result obf5 bj. getrumber(); ob -getmares(); cbs-getscore(); os.atsplay(); > tput: inter Sports Score: 80 oll No: 188 orks Obtatnes Total Score tr: 250 EBiassmacrciass = ‘cass that contains at last one pure vital function is ald to be abstract. A pure virtual function isa member function Le, declared in an abstract clas, but defined in Tderved clas. + An abstract class doesnot reate any ject andi contains one or more functions for hich there sno definition (¥e2 pure virtual function). © Tostdy function overloading | Toten abut operator overloading. both the base class and in the derived class. Compiler doesnot know what 1 which funetion to call: tn this class appropriate member Function ix selected to ‘Fun me. Fr example virtual function. bc rete Caps Toh CFP BORIC -Sem M162 [FEI compre Time POLYMORPHISM m= ‘+ Polymorphism, in Co, is implemented through overloaded functions and overloaded operators. + Function Overloading is alo referred to as functional polymorphism. The same funetion can perform a wide variety of tasks +The same function can handle different datatypes. When many functions with the same name bt different argument Ist ae defined then the function tobe invaked Corresponding 98 function allisknown during ample ime. ‘+ When the souree code is complled, the functions to be invoked are bound to the ‘compiler during compile ime, a to invoke which function depending upon the type fd number of arguments. Such a phenomenon Is referred to early binding ttle linking or compile time polymorphisn. PE Function overioading = Se pie th yo etn erect SEN me eines ‘cons tera cree the pero aunt ae ie Cs (paseceeis ealeieneg ete canon satan ee {Spun ante fans sd wih neg on nd ensan with aes td ‘Son ut function names Tis aod Peele Oveoning + uoreended fence fenconwho ue nan wo van cont iver parece pe +The fancionevning on be prflomed sng singe and many eject This owning 2 Pica ort] ny oes Sri oe spunea at srgunect iat + itor toc ao costs + One beet crease ‘Acalisgvanto dierent apt unctons + Accs gan to iltent apt uncon (eth each objec. ‘wt ov eject. Fig, 62: Faction Overoading + ules for overtonded functions: 1. Theargument list of each ofthe function instances must be diferent 2. The compiler doesnot use the return typeof the function to distinguish between function instances ‘+The Program 6 explains the concept of function overloading with many objects and Program 6.2 explains the concep with one single) abject. Program 61: Propram for funeton overioading with many abject. ‘Bncludecsostrean.1> ‘ putt: old adnan (int, Ant gy Ant ©) ‘ coutecrsum ts" ceprasece\ns > ‘old addnun (Float p, float 4) ‘ couteetsum Le"4cp + 9 ‘oid asémumCint p> double q) ‘ coutce' sum L8°Cep 6 gee" > int im) ‘est ott, ob, ob3; ba. adinun (5, 8, 38)5 ‘bn. aginue (2.5, 3.6)5 82 addr (25, 3.595 > output: ‘The difference in return type is nota consideration for function overloading, Program 62 Program for function overloading with single object. ‘ Wold addnun(int pint qy int #) ‘ {coutee" eum As"cepegerce*\ > jet read Cais Meh CP EEA ON Sam 64 Plympton old atdrun (float p, float @) t , Void addrum(int p> double a) t outee'sum se°cepiqee"\n ) % nt rain() ‘ > outpet: sm 46 28.5 Press any Key to continue = =. TEED operstoroeroning ese ieee eon ‘+ inCés, you can overload most operators so that they perform special operations ‘lative clases that you crete + Actually, Co tries to make user defined data types behave n much the same way as Satin ype ‘+ Forinstance, C++ permite us to add two varables of wer defined types with the same Syntax that sapped tothe basi types. Tls means that Crs has the alt to provide ‘the operators witha special meaning fora datatype The mechanism of giving sch speci meanings to an operators own as Operator Overioading. ‘+ Operators can be overloadedby creating operator functions. ‘+ An operator funtion defines the operations that the overleaded operator wil ‘erform relative to the class upon whieh wil work + Anoperator functions created using the heyword operator. + Aoperstor functions general frm is eturn type c1as5.nane:: operator op (arg-List) « 11 operations > ‘Where, return-type the typeof value returned by the speciid operation and opis ‘the operator blag overloadea bjt rte conc hgh CF BEA Sam) _67 3. When we want to call operator overloading function the syntax operator sign objectrae For example: For ealling + signs operator overloaded function we wills, 934; Here, isthe object ofa clas where operator overloading function is declared. [iE ties for overioading operators = ‘Although it looks simple to redefine the operators, there are certain restrictions {and/or limitations in overloading them. Some of them are listed below: 4 Only existing operators can be overionded. New operators caanot be crested. 2 The overioaded operator must have atleast one operand thats of user defined bee 3 We cannot change the basic meaning of an operator. That is we eannot redefine ‘the plus (1) operator to subtract one valu from the ther. 4 Overloaded operatrs follow the sytax rules ofthe eriginal operators that cannot teoveridden. 5 There are some operators that cannot be overloaded such as." et. {© Unary operators, overloaded by means of a member function, take no explicit arguments and return no explicit values. But those overloaded by means of ‘Bend function take ane reference argurient. 7. Binary operators overloaded through a member function take one explicit argument and thote which are overloaded through a frend function take two explicit arguments. 18. When using binary operstors overloaded through « member function, the lf ‘band operand must bean abject of the relevant cas. 9. Binary arithmetic operators uch a +, / st explicitly return a value, They ‘must not attempt to change thelr own arguments. 130, We cannot ue fiend functions to overload certain operates, which ar listed ‘below. However, member functions canbe ured taverioud them ‘= Assignment operator (0. uneion eal operator (1. Subscripting operator => class member access operator ner, frend eannct be sed. EM operator overioading Unary and Binary Oviladng Vary Operon: ‘The operators can be overloaded using wo different functions Le. through member functions and frend functions. ‘Acunary opertor overloaded using 2 member function takes no argument, whereas ‘an overloaded unary operator declared as friend function takes one argument je dana Teg 8A C4) Sm) _ 627 tym wold Overinaope:: display ( ) ‘ cout ce "ent ce x ce only tout ce "y=" cy ce endly > oe nain() 4 vertnadpr 55 scatsolayOs os ‘{Yovertoaaing unary °~" operator scdtsolay0s, ) output: eB overtoading Insertion (<<) and Extraction (>>) Operators We have already used the objects cn and cout (pre-defined Sn ostream ft forthe Input and output of data of various types. This Is possible only because the operators >> and <<.are overloaded to recognize all the basic C++ type +The» operator i overloaded in the letra class and << operator ie overoaded in the ortream cas, The istrears class overloads the >> operate forthe standard pes Tinttong. double, oat, char, aod char "(ting ‘+ Forxamplethe statement, cin >> x; call the appropiate >> operator function for the ieteam cin defined infosteama. An uses to dec this inp stream into the ‘mamory location represented by the arable. + Similarly, the ostream class overloads the late info z ‘ ‘ine rots shar nane(2 jet reed comp sgh CP BEACON Sem.) 68 meron pute: infec) « rane [0] = "0's > Friend Istreae & operatons(Astrean &, info); ‘friend ostream & operatorcc(ostrean &, info); ‘stream & operators(sstreae ‘ > ‘streas & operatorcc(ostrean 8S, tnfo 8d) ‘ secdsnanes » Ant natn () ‘ > output: TEE sting vaipaaton uring pro venting Ce pert rt aetna f pera tan bet pl {hosing ry mah sa he dca amber + opens eta eee a ee ces eT oe he ned cncp Trig NA) -Sem 420 ramen Ant mang) ‘ string st: stagetsara(), stestsplay(): return 6 » output: Enter string to be reversed Reversed string = RSE Press any key to continue ‘Program 6:10: verond the operator! to in ou the length of ie tring. inclufeciortrem.t> ES includeccont.t clase string ‘ har stele]; void geteata() ‘ > {nt operator 1 () ‘ tne Ve strten(ste eturn(l)t > vote ctsplay(s 2st: oie Strings: display() ‘ cout ject ete Cong hgh PP BEA -Sem. 621 emer Ant maint) ‘ stagetdata()s sicttsplayOs ees > ength of stringse rote any key to continue. ‘rogram 64% Write « program to overlond the + operator so that two Frings can be ‘oneatenated. For example si» abe, 52 pat then abe par = abcpae. ‘includectostresn-h> ‘Hneludeceonto:t lass string ‘ char str(20}; //ueber vorlable for string input bse ld Ingut() /eenber function t cautec"tnter your string: *: ln. getdinecstr,20); » oid atsplay() //nenber function for output 5 emesis “ese String operatore(string 5) //overloading ‘ string obs: streat (strate); Strepy(ebs-ser st); > # Ant maine) ‘ String strt,stra,st3; //ereating three objects serassneue(bs ser2-Snpu jn vad Caps sgh CF BOAO Som) _622 remeron [EE xuwnme potymonpnism on unsime polymorphism ir also called ar dynamic binding or Tate bind ‘Somatime, situation occre where function name and prototype i ame in bath ‘the base class and in the derived cass. Compiler doesnot know wit todo, which fonction toca inthis elas appropriate member function itelected torn ime. For ‘example virtual function. ‘+ To achive runtime polymorphism C++ supports a mechanism known ae virtual functions Dyzamle Binding ses the concept of polntrs, Le. It equtes to use of polsterto object TEEN ui Pinter reyes con fn dre reagan impel pate + moter mod The ber fn of each andesite acs 6 2 Feiner aed piste es ell «+ Theis pers en tpi parameter al member cin Therefore idea Searcy umacmes oe msens + Feed fancy to nts ei plies Ren ae bat mambo of Bienen trea ar pane ¢‘Srsapimer pinot ote fo ich he ection wt ced 1 tpimers ef’ pte sere thn eve ese 1 ibelmer te pimerPiming we cent Se of pce das. "sia Tern ges + Syme “+ very object has access to its own address through a pointer called this. When a ee reel ates catty pon a aes Soseace + Renaple heft al feecenererey merry + ont thnpertant apenas eee acto wich te Sondng ference oni sate nies uenie ncn wl rer he she hat ices member con open 2 Watee Berane c privat ‘har nane(40}: ec ort Caney Teg HA CAS) 628 symp pote vod get() ‘ fin 95 mane 9 marks > vot etsplay() ‘ this -> get cout names out ¢e "Vn Ranks = "cc ths > marks , dtsplay()s ezudisolay0s > output: Prwjeken 8 BEE Printer to objecis = Se ee nates seennren sarercons le nooo | ane : pubic eto, cin 99 4 >> yb > tc td Cone Teh PHA ots pat ‘ > , 6 pa sede pee ec ods en as = + no tha pase reenact pot ee = | Siaeeineeeeratemeremmnarcerne Parone erp erences a aera ge 2 ee ee Son aay ciao aes oe : oe se or : ; Oo aie : oduct mane = \e*ce panecend cout <6 "Price = \Ee prsees etd cane Tug 7 BA CAS) 25 Pemention ne maing) « product pty 62, tpt: pte = Bet; pLaetO: pu.asspiay(); mgt; p2.display(): exten; > output: Enter product rane ard price TB reine to Devived cases ‘We can use pointers not only to the base objects but also tothe objects of derived Classe pointes tothe objects of base cars are type compatible tothe objects of Served ease. + Therefore, a single pointer variable can be made to point to objects belonging to Aiferent clases. ‘+ Forevample if 8 isa base class and Dis derived class from then a pointer declared ‘pointer to Bean sso be pointe oD. + Consider the lowing declarations B+ epee; pte = 8, + Weean make ptr to point tothe objects follows: ‘ote = My ‘Tis is pevtocty valid with c++ because ¢ is an object derived from the class 8. However, there is problem in using cpr toaccess the public members ofthe derived dus, 4+ Using epee we can access only those members inherited from B and not the members ‘that originally Belongs to Dn case a member of D has the same name 25 one ofthe ‘members of any reference to that member by cpt will aways access the base cass embers. jt rn onc Thigh PPA -SomM)_ 627 yep cout = 03 ‘+ When a virtual function is made pure, any derived class must provide its own definition Ifthe derived cass fais to override the pure vstal function, comple ime ror wil occur. A class containing sucha pure virtual function i called an Abstract chase + Wecan define pure virtual function at “The functions which are only declared but not defined inthe base clas are caled as pure viral funcion’. Properties of Pare Virtual Function ‘+A ure virtual function has no implementation inthe base clas, hence a class with Dore virtal function cannot be instantiated + Apure virtual member function can be nvokedby ts derived cass + Ieisjust placeholder for derived clas. The derived classi eupposed tol thi empty function rogram 646; rogram for «pure ital function. include clertresm> teing namespace st class runber ‘ ‘nt vals public: youd set_val(int 4) ) rtun vid stan) = 65/7 pire virtua faction » Claes hoxton: pbc mater : wolic vetd shout) i fourcenncoabec ars at te rtd Canc Treg FHA CN fm] 68 ‘lass dectype: public number ‘ veld show ) ‘ covteevaleens > % ‘ pt: oud show) ‘ comtecoeteeval eens > un 0) sectype 6 hextype hi vset val 20) S.shou(): 1) Absplays 20 ~ dectnat eset _val 20); heshou(): 1) dtsphays 14 ~ nexadecinal evset_val(20)5 evshou(): 17 dtsplays 24 - octal > outpet: 20 “ ‘+ nthe above program as shown the base class, umber contains an integer called val ‘the function setval ) andthe pure virtual function show ). The derived clases Inextyp,dectype and cttype inherit mumber and refine show) that it outputs ‘the vale of vain each rerpective number bare i.e, hexadecma, decimal roca) [copes] Te Tounderstnd Cv ereame and Gv etream cases (© Tolearm about Unformatted 1/0 operations and Formated console /0 operations BE Tomdy Outpt formatting wing aniplaer. 15 Toundersiand wer defined manipulator (Cs defines ts ow object orented 1/0 system; i has ls own objet orlented way of handling data input and output. These input/Output operations are carried ou wing diferent stream cases and ter related functions. ‘+ Until now we have used the obec of the isteam clas (cn) and object ofestream ‘dass (outwith operators >> and << respectively. For formatting purpose we use tiferent streams and their fencions in C+ Ficus srmzans fs 10.11 ‘stream sequence of bytes. + stream acts either as a Souree from which the input data can be obtained oF a8 2 destination to whieh the output data canbe sent ‘+ Inc++tomanage the dataflow we have different stream classes, (fer Fig, 73) ‘+ ig. 7 shows stream classes for console VO. AL istream cass It ea derived class of os and hence, inherits the properties of 40s. defines input fanetions such as get(), petline() and read(_). In ‘dition, ithas an overloaded member funtion, stream extraction eperator>> to ‘ead data froma standard input device tothe memory items. 2. ostream class: Ite a cerived clas of los andhence inherits the properties of fos defines outpt functions suchas put(-) and weste( ). Im adition, i has an en Xj td cnp Tag PHA CN) -SenV]_73_ Mang aml 0 Options ‘+ Stream acts as an interface between the program and the Input/Output device ‘Therefore, C++ program handles data independeat ofthe devices used pice ut Sram sini Progen ast ance ae Seer — 171g. 72: Dea Steamein Cos Ei uwronnarrep vo operations PEE unrormatted 170 operators aa Se ios magn orcas elt ce moet + Thegeera amt orreadng het om he eye i ere vrtand rau any Cs predefined arable + Thissatennt inte progam meh compet wah input a fom Teton +The opeor>> reas the as character by character and asi tthe inetd bowen + Thera for th varie wile emit th encunter of wise oa arc Sat ott wan canon ye + Thegeera frm or dplying ata nee PEEL Untormatted 1/0 Functions Unload vo incon eine blo 1 gets eas a en ee pg ln om ag Strmterlnps/Ostat options tion + Tae pee Ac teers o eoeion 1 Wecan any son of pry tered th ta fr pow iar fotarocineec 2 puto: m= ‘+ Theclas ostream defines the member function put) whichis used to outpt line of textona sere character by character, ‘+ Thefuncion put, outputs one character ata time, + Syntax cout. put(char)s + example: ceut.put("s"); //Dispaysthe characters, ceut.put(eh)s __//Displaysthe contents ofa variable ch. ‘+ The variable ch must contain character value. We ean alge use number as an. argument tothe pat function ike caut.put(65);_//Displays character A. Since, the ASC value of character fais ‘rogram? Program for put function using ranespace std: int maint) ‘ ‘aut > with object cinas, ‘But cin can only read the strings that donot contain any white spaces, which means cn can read only single word at aime nota series of words line programming with Covie fm Program 7.3: Program for elie function ‘inclusecconso.n> nt wain() ‘ Int size = 405 char tite (50); cin.getLine(title, size); couteerEntared title 4s:"5 cout «en <¢ title; eeten(): return(@hs ‘tle sesconputer & writeo: 1 Write functions wsed toverite stof characters nt the file ‘The write isa member function of ostream clas ite ueed to dapay entire line on thesereen + Syntax ceutswrite (Line, st28); ‘where, lines the variable f which contents have tobe display and size is number of| ‘characters tbe display One important thing to note about write funtion yt dee not stop. displaying the characters automaticaly when NULL character 1s ‘encountered. ifthe sizes greater than the length of ine, then it displays beyond the ‘ound oftine thc etd Cnc Tough PBA CA Som M]_77_ Managing ole UO Operon, 5. endl ‘+ Theread function sed to read ase of characters form the fil + syntase ‘Aleoosect_nane-rend((ehor *) and vartable name; size of (variable nate): ‘Program 7.4: rogram forweite function ‘iretudecconto.h> nt ming) ‘ char mane [20]; fin 99 none cout.urite (rane, 10); exten return(@); > outpet: ress any key to continue © peek reads particular char from Me. 7 patbackO Itplaces the contre back o previous character ebtainedby get. 1 ignore: IRekips numberof characters while reading or writing ina fle 9. sizeof Ie gives size of memory required for storage For ecample:sizeof(c); where isa character soit requires 1byteofstorage. FORMATTED CONSOLE 1/0 OPERATIONS. ‘+ There are two types of functions are avallable in C++ for formating the output. + These are 41 0S clas functions 2. Manipulators. ‘+The 105 cass contains large numberof functions that would help us to format the utpet in number of ways ives... 1 Tolear rem Castes for File operations. |= Tostudy erent Fle operations (@ Tounderstand Fle updating wth random cess {© Tolearn Eror handling during le operations. ‘Tost command lin guest. tis dificult to handle large amount of data only with use of heyboard and srwen. So, weneed tostore data on secondary storage device as data structures called es ‘A computer system stores programs and data in secondary storage inthe form of ‘les A lesa cllection of rated information. Afi is a sequence of bits, bytes, lines or records whose meaning is defined by ts ‘creator and user. Alles mamedand referred toby its mame. ‘To define a file properly, i is necessary to consider the operations which can be performed on fles. The Operating System (0S) provides most ofthe essential fle ‘manipulation services such a rete open, wit, ea, reind, ose and delete. ‘A program typically involves data communication between the console and the program or between the fles and program or even both The program rust atleast perform data exchange between processor and main memary. Computer programs ace written to store the dat (a write operation on fl) and to ead the ata avead operation on le). computer program involves flowing two types of data communication ‘© Data transfer between thekeybeard/monitor (console) and the program. ‘© Datatransferbetween the program and the disk fle 4+ lg 81shows the concept of data communication. ey tj re conse CP BAIS. |_8S iblopesing sie = a El See aiers ce ter _ B: lpemreey ered ler eaty omen ter ae PINE cescmecereceuarinparayes ee eee Ferme i len henge SSE Sees 2. When fe opened for te ony ane le rented tere ise fest of ao «when we wat wit cera tet Information he le hl ected and Spend deen fe sant ete smn te fete feta be aoa + emeSlecubeoped inoremge 1 asce srie caress 2 opening fle sing peat) meter fnton. EERE opening rite using constructor * iorertoperorm fit pertns tefl shes open. As weno, ens i toed toniloran cecil tisteing ete, +: ies incine b col EKG aca waa'b st win nts won dee + Turco et lasing a onan otic arb ha ng ep Farrer rine rrieyerei eseereper am, Hfstrean obt ;//input cofstrean obz; output fetrean 005 7s an output ‘ie seream is identified by a fle name: Forexample, fstrean o21("stut.éat"); ‘This statement declares ob as an Ustream object and attaches for reading (input) as shown nF. 83. _ oo ig 8.3: np stream object bint ted conn heh BRA as suing ith ns + When the les open i append mode, then the new datas added at theend ofthe fle andoupet ptr aresettoendof he leas shown ni 88 Geren waren] Roe a oupu pre Pig. 8: Append Mote hie show the defn ations take place wit input and output pointers. HiEbrunctions for Manipulation of File Pointers seta mls member fncton of itream. mows gt ln inp ta speed vento + aqatan sng (setions apa seh) rr tne icc {mores thee pote byt rember 20 th pratt 2 ye intheesne ere 2 slat 7 mente cx ofiream, + mearpet ple taspeied eto. 3. telig(): ma 1 ilbmunber feo of hoean pe caret pton oa pt pen pecemmplr tong n= neg i Aare eran rest poston ot pete 4 saa a= Ree Pantene spain plane + rertample tapn (6, tots pelea ester ‘+ Here, the output pointer is moved to the end ofthe ile “stud and the value of? ives the numberof types in the fl, We also specify the offset with seeeg() and seeep() functions. + Syntax se0ke (offset, potnter direction): seekp (offeet, pointer direction); tet red Conc Thegh CP IBEA(N Sem. 836 ig + Where offset isthe number of bytes the Mle pointer is tobe moved from the location specified by pointer direction The pointer direction is one of the following defined in thetos cass: toxics eck rom beginingof the le tesssewe sek from current ction. session seek fromendof le + rorexample, = © tn.seea(o, for:t0a;—//0otostart (i) An.seekg(m, sos: :beg); Hrmave to (mn+3)” byte in the fle (U) Sncsetg(on,Sos:senl);//gobactward by mbyte from the end (0) imscorpate, Sor:sor); 17g forward m byte from curen poston. (@ nseeg(-1, fo::end); moves the get plnter 10 byes bacward ‘rom the endof hele, Program 87: Functions for manipulation of fle pointer. ‘ncluseciostrean. > nt wain() ‘ stream infcles netesopen("stul” 105: :4n "ios: :binary): sfaunette) « cerreetteror openteg”ceendl; exit(ay; Anfile.seokg (0, S0s::end); coutee"File size ="ecinfile.tel26()5 {nfite.close( > output Here, keyword "er? ie used for displaying error. (EEL mz veparinc wir ranpom access ‘+ Random access means moving the file pointer directly o any location in the le Instead of moving sequentially ‘+ Therandom aces techniques often used with the database Mes jt red Cony ev CP BRAIN Sam) 120 ene epaated file 48 ‘inding file size & no. of objects no, oF objects = 3 1+ When we use ies different errors occur such 8 1 Afletobe opened doesnt exist. 2. Invalid filename, 3. Aflename used fr anew fle may already exist. 44, Insutfclent dis space ‘+ Hence, once the Mle is opened it has tobe closed and reopen is possible using same ‘+ Weean se following functions for error handing during le operation: © dearer function © feof function © ferrr function (© peror function 4. Theclearerr function: ‘The clearerr function clears the end-of-flle and error indicators forthe steam pointed toby stream. include cstdio.h> Vola clesrere(FILE *stream): 2. The feof function ‘The fof fonction tests the end-f-fle ndctor fr the steam pointed toby steam land returns nonzero if and only if the end-of Ale indicator Is set for stream, ‘taro rebar bee. Ane Feof(FILE tetrean) 2. The error function ‘+The frzor function tests the error indicator for the steam pinta to by stream and ‘returns nonzero if and only Ifthe eror Indicator Is set for stream, otherwise It include cetdtosh> Ant ferror(FILE *streae): jc dana eg HAC) Sm) 828 igh he |. Theperror function +The perror function maps the error number in the integer expresion erro toa fervor mestage It wtes 1 sequence of characters othe standard errr stream thus: ‘et f+ le nota nll pointer and the character pointed to by # 4 not the nll, huaracter, the string polnted toby s followed by a colon () and a space: then an {ppropeiate error message string flowed by 2 newline character. The contents of {he eror message ae the same se thoce returned by the sterror function withthe Argument emo, which are implementation defined include estato.4> wold pervor(const char *5) FEE comman une ancuMENTS ‘ile names may be supplied as argument tothe main) atthe tne of invoking the program, these argument are known ax Command Line Argument. + These arguments are called as command lin argument because they are pased from the commandline during runtime ‘+ Themain) function lok ike this: main (int argc, char * argv) + tm above the function main() can have two arguments, named arge (Argument ‘ounter) and argy (Argument vector), where argv isan aray of pater to stings fd arg is an integer whose value is equal tothe numberof strings to which are¥ points + When the programs executed, the strings on the commandline sre passed to main() + Forexample Filecpy rource.c destination.c + Here, argecontain: ‘snev0]-» base addres of tring flecpy. raft) -» ase addres of tring "source argcf2]—> base addres of string “destination” Program 8.3: Program te copy file using commandline argument Ant main (int argc, char * arev()) ‘ 1 Gree G “> secs > har oh: Sfstrean Fins ‘in.open (arge(4D): tt red Cnc Tragh PAA) 822 stein sa10) ented tat coms cae, > foutopen Core2D Herons ta) ¢ coun ot open destination” ea: ) cesnecrin) « sin.geions fotos > > output TMs $8 Fle apy progam //sourcec Tis As Fle emy proton /Haatioation.e rogram 840: Courting the numberof vowel in the text fe inclodecftrem > tote mind 4 int count; inp Cig.) Seton (x tex) Sie’ cincor) ‘ star oh = (onan) sae; eT cece Hemet IL abe » inicio ering fe output: ‘nds 4s progras to Aisooue #810 No. of vowels = 12 shen screen ‘Program 811 Write program to count number of character, lines and words ina fe = sincludectostrese.h> sincludectstresn.h> sincludecseaise.t> wold ming) 4 Ime noc = 6; nol = 5 new = 8; ¢strean ny seyFeopen( "count cat"); sestec ‘ yftae.get(emns sF(eneeof) se((ehee WW") I] (ehee'\t) s¢(enen"\n") > coutccrn. of words = “ ofstrean out (dt); tput: snste (an) ‘ sn ger(e cout. put(eh)s > > This ts Fale copy proman input file THis 15 file copy program /outut file ‘A file i a colection of related or asoclaied data on a paricalr area ofthe orage device Text fles and binary files are the to diferent types of ies, ‘data of files stored nthe form of readable and printable characters then the fle {shown a text le file contains worreedable character in binary code then the fei called binary ie ‘The data in text file estore in the form of characters, en ASC code, in binary Ales the data istored in terms ofa sequence of byes, Le, InO'.ands File handling concept in C++ language is used for store a data permanently in computer Using fle handling we can store the data in secondary tertoryQard dst). ‘Astream e general name given toa low of data. ec ted on Teh PHBA Sam. 8.2 rp, + A function template behaves lke a function except that the template can have rgumentsof many diferent types ‘+ There are two kinds of templates one is function template and anther is cass template +) Acass template provides a specification fr generating eases based on parameter ‘hss termplates are commonly used to implement container. ‘+A cass template is instantiated by passing a given set of types to it as template CLASS TEMPLATES ‘ke fonction templates, dass templates are Aiferent data ype. + Gee cast templates, rents clas which contain one or more ner data types +The ayntax for resting cas template ie 0 used to declare to operate on "ere, lass data items and functions arguments are of template type + Ferexample: ‘ 1 a) arr 03 sola ads (const T dete): Trenove (void): votd show 11185 45 used to change & + Normally without template we declare clas of char array a: char te}; pues ares ‘old ada (const char & ele); har remove (vod); wold shows je td Comps regh CP BHAA em) 94 a Ant main () « sme 105, $06, ke eng 1-10, 9-5, 05 egetnoxeint>(h,3)s egetraxclong>(1,9) cout «ek ce ends cout <& ne ends ‘Gre provides a facility for function templates that allow you to write one function whichis act ab template for a number of functions which are performing sar tasks. + Afunction template will not use actual type of arguments butItuse generic typeasa lacebolder impli when we make a al ta function. For each version af data pe, ‘the compiler generates a copy ofthat function. For example: when intoger version Is called, the compiler generates “add” function with integer datatype and Soon. +The general syntax ‘enplate retirn type func_nane (argvents) ‘Lreamp ate Function +The function template is preceded by keyword template and a list of template type arguments, (generic datatypes). The template function uses variables whose data ‘types are known only when a calls made. Program 9.4: Write function template o find the biggest of two numbers, ‘includecsostrean.t> ‘reludecconto.h> tewplatecclass > Teg (ra, TS) 4s (ae) return (2)5 flee retuen (05 > he red Cnc Thigh PP BEA (fom. 97 amp Ant maint) ‘ coutee"Wn bigger no. 15:"cebLg(20, 15) enplatecelass 90 ole SwapOX 8a, X 80) //y reference ‘ bo tem: > Ant main() ‘ coutecrtnter x 8 y before swapping cen, eimonnys saapcrs Ds char et) ©25 snap (Cte 2); cautectafter saapping” output: Enter x and y before swapping after sopping: ec id cane Treg HK CAS Yb Tempe Program 9.9: To find biggest of two stings Le. bg (A, "then compiler give error menage Ths problem we cn salve using overided function template ‘overloaded function template ‘rclude clos sng namespace ste; char tbig (ehar *%, char *y) ‘ 4 (streap (4, ¥>0) false return 95 > Tig (tx, « suey false return 95 > Ant maint) ‘ lager no. is:"ccbig (30, 20)ccendl; coutecralgger L8:*cablg (*A*, "85 > output: Bigger no. As: 20 ger ts FEM nnopuction oF ExceTion HANDLING = ‘+ Wes we work with program or compile the program, we normaly get logic eros or syntactl error We can detect thee errors by debugging. We aften cme across the ‘errors other than logic and syntactic eros. They are known as exceptions. Exceptions are run-time errors that a program encounters while exzewting. Fer example, Array outer bounds divide by are ‘+ C+4 provides ulti ero handling mechanism thats called Exception Handling. ‘Using exception handling you can more easly manage and respond to run-time be td Cnc Tigh PNA) 92 omg ‘The purpose of exception handling mechanism is to detect the exception in the fallowing way AL Find the run-time problem te exception. 2 Inform thatan erzorhas occurred by throwing the exception 3. Getthe error information from compiler Le. catch the exception 4nd the exception in catch block. EX Elexception Handling bs 3] ‘Cr+ exception handling mechanism utes thre heywords try, ateh and throw. - tryblock contains program statements that we want to monitor for exception © When an exception i detected it thrown using a throw statement in the ty The exception is caught using eatch Typically, acatch(.)Block is used to log “errorsand perform special cleanup belore program execution stopp. © Any exception must be caught by a catch statement that immediately follows the ‘ry statement that throws the exception. ‘The general frm of try and catch s piven below: wy ‘ Uiery bree throw exception /Veetects and throws exception > caten(typet arg) ‘ eaten block ) caten(type2 arg) ‘ eaten block > cxten(typeh are) ‘ eaten voce >

You might also like