C++ is a widely used general-purpose programming language that was developed in the 1970s as an enhancement to the C programming language. It combines features of both high-level and low-level languages. C++ programs must be compiled into machine-readable code before being executed by a computer's CPU. Compilation involves translating the human-readable C++ code into machine code. This process makes C++ portable to different computer architectures. C++ remains one of the most popular programming languages due to its wide application in systems software, applications, drivers, and games.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
45 views47 pages
Saraswati Computer Centre
C++ is a widely used general-purpose programming language that was developed in the 1970s as an enhancement to the C programming language. It combines features of both high-level and low-level languages. C++ programs must be compiled into machine-readable code before being executed by a computer's CPU. Compilation involves translating the human-readable C++ code into machine code. This process makes C++ portable to different computer architectures. C++ remains one of the most popular programming languages due to its wide application in systems software, applications, drivers, and games.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 47
1.
SARASWATI COMPUTER CENTRE
Welcome to Saraswati Education Centre Saraswati Education Centre was established on 31st of July 2003 vide Jammu & Kashmir ovt! "e#istration $o! %C&11&12'(' )ated 31&0*&2003! +his ,nstitute is an erstwhile ,nstitute of Com-uter and .cademic Education and en/oys -rivile#e of rich e0-erience in the field of Education! 1ur ob/ectives are 2 +o 3rovide access to 4uality education to all those who see5 it6 irres-ective of a#e6 re#ion or formal 4ualifications! "ela0ed entry re#ulations! 7le0ibility in choosin# the courses from wide ran#e of disci-lines! )emocrati8in# education by ma5in# to the masses! 1 Accreditation S.".SW.+, E)9C.+,1$ CE$+"E has #ot accredited with KS19 for runnin# 9niversity courses of :ana#ement6 ,nformation +echnolo#y 3ro#rams and Com-uter .--lication 3ro#rams since )ec 200; for the benefit of all as-irants6 lobal 1-en 9niversity6 $a#aland from June 200(6 <hartiya Shi5sha 3arishad and Sin#hania 9niversity as 3lacement and Counsellin# centre for various courses! S.".SW.+, E)9C.+,1$ CE$+"E is also certified by ,S1 =00122000 Certification as 4uality and standards followed by the or#ani8ation! 2 Courses of Saraswati Computer Centre : COURSES DURATION FEES 1ffice 1-erations 3 months 1;00&> C&C?? 2 month 2;00&> %isual <asic 2 months 2;00&> [email protected] and .--licationsA 2 months 3000&> 7o0 3ro 2 months 1;00&> %isual C?? 2 months 2;00&> !$et 3ro#rammin# ' months ;000&> @%isual ! net 6 CB6 .S3 !$etA .ccountin# 3ac5a#e 3 months 3C00&> @:anual .&c6 +ally6 <usyA +ally 1 month 2000&> <usy 1 month 2000&> E0>$e0t eneration 1 month 2000&> )+3 2 months 1(00&> @3a#e:a5er6 Corel )rawA 3hotosho- 1 month (00&> 1racle 1 1&2 month 1;00&> D+:E@Web )esi#nin#A 2 months 2;00&> @D+:E6 F:E6 7ront3a#eA %<Scri-t&JavaScri-t 1 month 1000&> .S3 1 1&2 month 1;00&> 3 ' 2. C++ C?? @read as GC 3lus 3lusGA is a statically ty-ed6 free>form6 multi>-aradi#m6 com-iled6 #eneral>-ur-ose -ro#rammin# lan#ua#e! ,t is re#arded as a middle>level lan#ua#e6 as it com-rises a combination of both hi#h>level and low>level lan#ua#e features! ,t was develo-ed by </arne Stroustru- startin# in 1=*= at <ell Eabs as an enhancement to the C -ro#rammin# lan#ua#e and ori#inally named GC with ClassesG! ,t was renamed to C?? in 1=(3! C?? is widely used in the software industry6 and remains one of the most -o-ular lan#ua#es ever created! Some of its a--lication domains include systems software6 a--lication software6 device drivers6 embedded software6 hi#h>-erformance server and client a--lications6 and entertainment software such as video #ames! Several #rou-s -rovide both free and -ro-rietary C?? com-iler software6 includin# the $9 3ro/ect6 :icrosoft6 ,ntel6 <orland and others! +he lan#ua#e be#an as enhancements to C6 first addin# classes6 then virtual functions6 o-erator overloadin#6 multi-le inheritance6 tem-lates6 and e0ce-tion handlin# amon# other features! .fter years of develo-ment6 the C?? -ro#rammin# lan#ua#e standard was ratified in 1==( as ,S1&,EC 1'((221==(! +hat standard is still current6 but is amended by the 2003 technical corri#endum6 ,S1&,EC 1'((222003! +he ne0t standard version @5nown informally as C??00A is in develo-ment! +odays com-uters are incredibly fast6 and #ettin# faster all the time! Het with this s-eed comes some si#nificant constraints! Com-uters only natively understand a very limited set of instructions6 and must be told e0actly what to do! +he set of instructions that tells a com-uter what to do is 5nown as software! +he com-uter machinery that e0ecutes the instructions is the hardware! . com-uterIs C39 is inca-able of s-ea5in# C??! +he very limited set of instructions that a C39 natively understands is called machine code6 or machine lan#ua#e6 or an instruction set! Dow these instructions are or#ani8ed is beyond the sco-e of this ; introduction6 but it is interestin# to note two thin#s! 7irst6 each instruction is com-osed of a number of binary di#its6 each of which can only be a 0 or a 1! +hese binary numbers are often called bits @short for binary di#itA! 7or e0am-le6 the :,3S architecture instruction set always has instructions that are 32 bits lon#! 1ther architectures @such as the 0(C6 which you are li5ely usin#A have instructions that can be a variable len#th! 7or e0am-le6 here is a 0(C machine lan#ua#e instruction2 10110000 01100001 Second6 each set of binary di#its is translated by the C39 into an instruction that tells it to do a very s-ecific /ob6 such as com-are these two numbers6 or -ut this number in that memory location! )ifferent ty-es of C39s will ty-ically have different instruction sets6 so instructions that would run on a 3entium ' would not run on a :acintosh 3ower3C based com-uter! <ac5 when com-uters were first invented6 -ro#rammers had to write -ro#rams directly in machine lan#ua#e6 which was a very difficult and time consumin# thin# to do! <ecause machine lan#ua#e is so hard to -ro#ram with6 assembly lan#ua#e was invented! ,n an assembly lan#ua#e6 each instruction is identified by a short name @rather than a set of bitsA6 and variables can be identified by names rather than numbers! +his ma5es them much easier to read and write! Dowever6 the C39 can not understand assembly lan#ua#e directly! ,nstead6 it must be translated into machine lan#ua#e by usin# an assembler! .ssembly lan#ua#es tend to be very fast6 and assembly is still used today when s-eed is critical! Dowever6 the reason assembly lan#ua#e is so fast is because assembly lan#ua#e is tailored to a -articular C39! .ssembly -ro#rams written for one C39 will not run on another C39! 7urthermore6 assembly lan#ua#es still re4uire a lot of instructions to do even sim-le tas5s6 and are not very human readable! Dere is the same instruction as above in assembly lan#ua#e2 mov al6 0C1h +o address these concerns6 hi#h>level -ro#rammin# lan#ua#es were develo-ed! C6 C??6 3ascal6 .da6 Java6 Javascri-t6 and 3erl6 are all hi#h level lan#ua#es! 3ro#rams written in C hi#h level lan#ua#es must be translated into a form that the C39 can understand before they can be e0ecuted! +here are two -rimary ways this is done2 com-ilin# and inter-retin#! . com-iler is a -ro#ram that reads code and -roduces a stand>alone e0ecutable that the C39 can understand directly! 1nce your code has been turned into an e0ecutable6 you do not need the com-iler to run the -ro#ram! .lthou#h it may intuitively seem li5e hi#h> level lan#ua#es would be si#nificantly less efficient than assembly lan#ua#es6 modern com-ilers do an e0cellent /ob of convertin# hi#h>level lan#ua#es into fast e0ecutables! Sometimes6 they even do a better /ob than human coders can do in assembly lan#ua#eJ Dere is a sim-lified re-resentation of the com-ilin# -rocess2 Fig. 2.1 : Co!i"ing Proce## .n inter-reter is a -ro#ram that reads code and essentially com-iles and e0ecutes @inter-retsA your -ro#ram as it is run! 1ne advanta#e of inter-reters is that they are much easier to write than com-ilers6 because they can be written in a hi#h>level lan#ua#e themselves! Dowever6 they tend to be less efficient when runnin# -ro#rams because the com-ilin# needs to be done every time the -ro#ram is run! 7urthermore6 the inter-reter is needed every time the -ro#ram is run! Dere is a sim-lified re-resentation of the inter-retation -rocess2 Fig. 2.2 Inter!retation Proce## * .ny lan#ua#e can be com-iled or inter-reted6 however6 traditionally lan#ua#es li5e C6 C? ?6 and 3ascal are com-iled6 whereas Kscri-tin#L lan#ua#es li5e 3erl and Javascri-t are inter-reted! Some lan#ua#es6 li5e Java6 use a mi0 of the two! Di#h level lan#ua#es have several desirable -ro-erties! 7irst6 hi#h level lan#ua#es are much easier to read and write! Dere is the same instruction as above in C&C??2 a M =*N Second6 they re4uire less instructions to -erform the same tas5 as lower level lan#ua#es! ,n C?? you can do somethin# li5e a M b O 2 ? ;N in one line! ,n assembly lan#ua#e6 this would ta5e ; or C different instructions! +hird6 you donIt have to concern yourself with details such as loadin# variables into C39 re#isters! +he com-iler or inter-reter ta5es care of all those details for you! .nd fourth6 they are -ortable to different architectures6 with one ma/or e0ce-tion6 which we will discuss in a moment! Fig. 2.$ : Arc%itect&re +he e0ce-tion to -ortability is that many -latforms6 such as :icrosoft Windows6 contain -latform>s-ecific functions that you can use in your code! +hese can ma5e it much easier to write a -ro#ram for a s-ecific -latform6 but at the e0-ense of -ortability! ,n these tutorials6 we will e0-licitly -oint out whenever we show you anythin# that is -latform s-ecific! ( $. A FEW COMMON C++ PRO'(EMS ,n this section6 weIll address some of the common issues that new -ro#rammers seem to run across with fairly hi#h -robability! +his is not meant to be a com-rehensive list of com-ilation or e0ecution -roblems6 but rather a -ra#matic list of solutions to very basic issues! ,f you have any su##estions for other issues that mi#ht be added to this list6 -ost them in the comments section below! 3roblem 12 When e0ecutin# a -ro#ram from the ,)E6 the console window blin5s and then closes immediately! .nswer 12 Some com-ilers @e#! <loodshedIs )ev C??A donIt automatically -ause the console screen after the -ro#ram has finished e0ecutin#! ,f this is the case with your com-iler6 the followin# two ste-s will fi0 your -roblem2 7irst6 add the followin# line near the to- of your -ro#ram2 Binclude PiostreamQ Second6 add the followin# code at the end of the main@A function @ri#ht before the return statementA2 cin!clear@AN cin!i#nore@2;;6 RSnRAN cin!#et@AN +his will cause your -ro#ram to wait for you to -ress a 5ey before continuin#6 which will #ive you time to e0amine your -ro#ramIs out-ut before your com-iler closes the console window! 1ther solutions6 such as the commonly su##ested system@L-auseLA solution may only wor5 on certain o-eratin# systems! = 3roblem 22 When com-ilin# with :icrosoft %isual C??6 you #et the followin# error2 Kc2Svc-ro/ectsStest!c--@2C3A 2fatal error C10102 une0-ected end of file while loo5in# for -recom-iled header directiveL .nswer 22 +his error occurs when the :icrosoft %isual C?? com-iler is set to use -recom-iled headers but one of your C?? code files does not include the stdaf0 header as the first line! +o fi0 this -roblem6 sim-ly locate the file -roducin# the error @in the above error6 test!c-- is the cul-ritA6 and add the followin# line at the very to- of the file2 Binclude Gstdaf0!hG .lternatively6 you can turn off -recom-iled headers! 3roblem 32 When tryin# to use cin or cout6 the com-iler says cin or cout is an Kundeclared identifierL .nswer 32 7irst6 ma5e sure you have included the followin# line near the to- of your file2 Binclude PiostreamQ ,n any function where you use use cin or cout6 include the followin# line2 usin# names-ace stdN 3roblem '2 When tryin# to use endl to end a -rinted line6 the com-iler says end1 is an Kundeclared identifierL :a5e sure you do not mista5e the letter l @lower case EA in endl for the number 1! endl is all letters! , recommend usin# a font that ma5es it clear the differences between the letter lower case E6 u--er case i6 and the number 1! .lso the letter ca-ital o and the number 8ero can easily be confused in many fonts! +here is a hu#e list of -ro#rammin# fonts here! 3roblem '2 :y -ro#ram com-iles but it isnIt wor5in# correctly! What do , doT 10 .nswer '2 )ebu# itJ Hou can find information on how to debu# -ro#rams in a--endi0 .6 s-ecifically sections .!' and .!;! Hou will -robably find the debu##in# sections more com-rehensible after readin# a few more cha-ters6 but , wanted to ma5e you aware of their e0istence now for future reference! 1!1 U Structure of a -ro#ram ,nde0 0!C U Com-ilin# your first -ro#ram 3rint +his 3ost +his entry is filed under C?? +utorial! Hou can follow any res-onses to this entry throu#h the "SS 2!0 feed! Hou can leave a res-onse6 or trac5bac5 from your own site! ;1 "es-onses to K0!* U . few common C?? -roblemsL Comment by Jason 200*>12>1* 02222222 3roblem 12 When e0ecutin# a -ro#ram from the ,)E6 the console window blin5s and then closes immediately! +he ide ,Im usin# is %isual C !$E+ 2002! +his ide has -roblem 1! +o fi0 the -roblem , include the followin# command at the end of the main@A function before the return statement! system@L-auseLAN V 9nfortunately6 this only wor5s on the Windows o-eratin# system! +he system@A function tells the o-eratin# system to e0ecute whatever the -arameter is >> in this case6 a command named G-auseG! 1n Windows6 this waits for user in-ut! 1n other o-eratin# systems @such as linu0A6 the -ause command does somethin# else entirely! Dowever6 if you are only 11 -ro#rammin# on Windows and not distributin# your source code6 you may find this an easier solution while learnin#! >.le0 W "e-ly to this comment
Comment by fo4 200*>12>1* 0*22;2'= .nother #reat way to #et a -ro#ram to -ause is to re4uire a user in-ut @cinA! 9sin# a menu>ty-e interface that re4uires the user to select an o-tion for Ke0itin#L wor5s well! ,Im only a be#inner6 but for sim-le calculators that ,Ive created6 this wor5s well! "e-ly to this comment
Comment by Jason 200*>12>1( 1'2102'' ,n order to #et the screen to -ause before e0itin# the -ro#ram6 does the code2 cin!clear@AN cin!i#nore@2;;6 RSnRAN cin!#et@AN have any advanta#es over /ust usin# cin QQ my%ariableN , have so much to learn! 2A "e-ly to this comment
Comment by .le0 @adminA 200*>12>1( 1'22(2'1 Jason6 #ood 4uestion! DereIs a sim-le -ro#ram that illustrates why cin QQ my%ariable is not the best way to -ause2 12 Binclude PiostreamQ int main@A X usin# names-ace stdN && .llocate a buffer to hold user in-ut char bufV2;;W M X 0 YN && We only want one letter cout PP GEnter a letter2 GN cin QQ bufV0WN && 3ause and wait for user in-ut char ch,#noreN cout PP G3ausin#G PP endlN cin QQ ch,#noreN return 0N Y 7irst6 cin QQ ch,#nore i#nores the enter 5ey if the user does not -rovide any other in-ut! Hou can verify this by hittin# enter when the cin QQ ch,#nore line is bein# e0ecuted! 1n the other hand6 cin!#et@A acce-ts the enter 5ey as valid in-ut! <ut -erha-s more im-ortantly is the second -henomena that occurs when more characters are -laced into the in-ut stream @cinA than are read out! When as5ed for a letter in the above -ro#ram6 enter more than one letter and watch what ha--ens! 13 EetIs say you enter KabcdeL! cin QQ bufV0W reads the ZaI character6 but KbcdeL are still left in the in-ut stream! Conse4uently6 when the code #ets to cin QQ ch,#nore6 it reads the waitin# ZbI character out of the in-ut stream and doesnIt -ause at allJ +he 3 ste- -rocess is a little more fool-roof! 7irst6 cin!clear@A clears any errors the user may have caused by -rovidin# invalid in-ut in the -ast! Second6 cin!i#nore@2;;6 RnRA #ets rid of u- to 2;; waitin# characters in the in-ut stream @or until a n is encounteredA6 which is almost always #oin# to be enou#h to clear out the in-ut stream! 7inally6 we use cin!#et@A to wait for a character! Since we /ust cleared the in-ut stream6 there are no characters waitin#! Conse4uently6 the -ro#ram will wait for the user to enter somethin#! ,n ==[ of the cases you encounter6 cin QQ my%ariable will -robably wor5 e0actly as you e0-ect! <ut since the 3 line method is #enerally more fool-roof and isnIt -articularly burdensome to im-lement6 ,Id say itIs the su-erior solution! 1' ). STRUCTURE OF A PRO*RAMMIN* . com-uter -ro#ram is a se4uence of instructions that tell the com-uter what to do! Statements and expressions +he most common ty-e of instruction in a -ro#ram is the statement! . statement in C?? is the smallest inde-endent unit in the lan#ua#e! ,n human lan#ua#e6 it is analo#ous to a sentence! We write sentences in order to convey an idea! ,n C??6 we write statements in order to convey to the com-iler that we want to -erform a tas5! Statements in C?? are terminated by a semicolon! +here are many different 5inds of statements in C??! +he followin# are some of the most common ty-es of sim-le statements2 1.int x; 2.x = 5; 3.cout << x; int 0 is a declaration statement! ,t tells the com-iler that 0 is a variable! .ll variables in a -ro#ram must be declared before they are used! We will tal5 more about variables shortly! 0 M ; is an assi#nment statement! ,t assi#ns a value @;A to a variable @0A! cout PP 0N is an out-ut statement! ,t out-uts the value of 0 @which we set to ; in the -revious statementA to the screen! +he com-iler is also ca-able of resolvin# e0-ressions! .n e0-ression is an mathematical entity that evaluates to a value! 7or e0am-le6 in math6 the e0-ression 2?3 evaluates to the value ;! E0-ressions can involve values @such as 2A6 variables @such as 0A6 o-erators @such as ?A and functions @which return an out-ut value based on some in-ut valueA! +hey can be sin#ular @such as 26 or 0A6 or com-ound @such as 2?36 2?06 0?y6 or @2?0AO@y>3AA! 7or e0am-le6 the statement 0 M 2 ? 3N is a valid assi#nment statement! +he e0-ression 2?3 evaluates to the value of ;! +his value of ; is then assi#ned to 0! 1; Functions ,n C??6 statements are ty-ically #rou-ed into units called functions! . function is a collection of statements that e0ecutes se4uentially! Every C?? -ro#ram must contain a s-ecial function called main@A! When the C?? -ro#ram is run6 e0ecution starts with the first statement inside of main@A! 7unctions are ty-ically written to do a very s-ecific /ob! 7or e0am-le6 a function named :a0@A mi#ht contain statements that fi#ures out which of two numbers is lar#er! . function named Calculaterade@A mi#ht calculate a studentIs #rade! We will tal5 more about functions later! Libraries Eibraries are #rou-s of functions that have been K-ac5a#ed u-L for reuse in many different -ro#rams! +he core C?? lan#ua#e is actually very small and minimalistic U however6 C?? comes with a bunch of libraries6 5nown as the C?? standard libraries6 that -rovide -ro#rammers with lots of e0tra functionality! 7or e0am-le6 the iostream library contains functions for doin# in-ut and out-ut! )urin# the lin5 sta#e of the com-ilation -rocess6 the libraries from the C?? standard library are the runtime su--ort libraries that are lin5ed into the -ro#ram @this will be discussed further in lesson 1!'A! Taking a look at a sample program $ow that you have a brief understandin# of what statements6 functions6 and libraries are6 letIs loo5 at a sim-le hello world -ro#ram! Consider our hello world -ro#ram2 1.#include <iostream> 2. 3.int main() 4.{ 5. using namespace std; . cout << !"ello #orld$! << endl; %. return &; 1C '.( Eine 1 is a s-ecial ty-e of statement called a -re-rocessor directive! 3re-rocessor directives tell the com-iler to -erform a s-ecial tas5! ,n this case6 we are tellin# the com-iler that we would li5e to use the iostream library! +he iostream library contains code that tells the com-iler what cout and endl do! ,n other words6 we need to include the iostream library in order to write to the screen! Eine 3 declares the main@A function6 which as you learned above6 is mandatory! Every -ro#ram must have a main@A function! Eines ' and ( tell the com-iler which lines are -art of the main function! Everythin# between the o-enin# curly brace on line ' and the closin# curly brace on line ( is considered -art of the main@A function! Eine ; is our first statement @you can tell itIs a statement because it ends with a semicolonA! .s you learned in the e0-lanation for line 16 cout and endl live inside the iostream library! Dowever6 within iostream6 they live inside a s-ecial com-artment named std @short for standardA! +his usin# statement tells the com-iler to loo5 inside a com-artment named std if it canIt find cout or endl defined anywhere else! ,n other words6 this statement is also necessary so the com-iler can find cout and endl6 which we use on line C! Eine C is our out-ut statement! Cout is a s-ecial ob/ect that re-resents the console&screen! +he PP symbol is an o-erator @much li5e ? is an o-eratorA called the out-ut o-erator! Cout understands that anythin# sent to it via the PP o-erator should be -rinted on the screen! Endl is a s-ecial symbol that moves the cursor to the ne0t line! Eine * is a new ty-e of statement6 called a return statement! When an e0ecutable -ro#ram finishes runnin#6 it sends a value to the o-eratin# system that indicates whether it was run successfully or not! +he return value of main@A is used for this -ur-ose! +his -articular return statement returns the value of 0 to the o-eratin# system6 which means Keverythin# 1* went o5ayJL! $on>8ero numbers are ty-ically used to indicate that somethin# went wron#6 and the -ro#ram had to abort! We will discuss return statements in more detail when we discuss functions! Conclusion .ll of the -ro#rams we write will follow this tem-late6 or a variation on it! We will discuss each of the lines above in more detail in the u-comin# sections! Quiz +he followin# 4ui8 is meant to reinforce your understandin# of the material -resented above! 1A What is the difference between a statement and an e0-ressionT 2A What is the difference between a function and a libraryT 3A What symbol do statements in C?? end withT 1( +. ,ISTOR-
</arne Stroustru-6 creator of C?? Stroustru- be#an wor5 on RC with ClassesR in 1=*=! +he idea of creatin# a new lan#ua#e ori#inated from Stroustru-Rs e0-erience in -ro#rammin# for his 3h!)! thesis! Stroustru- found that Simula had features that were very hel-ful for lar#e software develo-ment6 but the lan#ua#e was too slow for -ractical use6 while <C3E was fast but too low>level to be suitable for lar#e software develo-ment! When Stroustru- started wor5in# in .+&+ <ell Eabs6 he had the -roblem of analy8in# the 9$,F 5ernel with res-ect to distributed com-utin#! "ememberin# his 3h!)! e0-erience6 Stroustru- set out to enhance the C lan#ua#e with Simula>li5e features! C was chosen because it was #eneral>-ur-ose6 fast6 -ortable and widely used! <esides C and Simula6 some other lan#ua#es that ins-ired him were .E1E C(6 .da6 CE9 and :E! .t first6 the class6 derived class6 stron# ty-e chec5in#6 inlinin#6 and default ar#ument features were added to C via Cfront! +he first commercial release occurred in 1ctober 1=(;! ,n 1=(36 the name of the lan#ua#e was chan#ed from C with Classes to C?? @?? bein# the increment o-erator in C and C??A! $ew features were added includin# virtual functions6 function name and o-erator overloadin#6 references6 constants6 user>controlled free>store memory control6 im-roved ty-e chec5in#6 and <C3E style sin#le>line comments with two forward slashes @&&A! ,n 1=(;6 the first edition of +he C?? 3ro#rammin# Ean#ua#e was released6 -rovidin# an im-ortant reference to the lan#ua#e6 since there was not yet an official standard! "elease 2!0 of C?? came in 1=(=! $ew features included multi-le inheritance6 abstract classes6 static member functions6 const member functions6 and -rotected members! ,n 1==06 +he .nnotated C?? "eference :anual was -ublished! +his wor5 became the basis for the future standard! Eate addition of features included tem-lates6 e0ce-tions6 names-aces6 new casts6 and a <oolean ty-e! .s the C?? lan#ua#e evolved6 a standard library also evolved with it! +he first addition to the C?? standard library was the stream ,&1 library which -rovided facilities to re-lace the traditional C functions such as -rintf and scanf! Eater6 amon# the most si#nificant additions to the standard library6 was the Standard +em-late Eibrary! 1= C?? continues to be used and is one of the -referred -ro#rammin# lan#ua#es to develo- -rofessional a--lications! +he lan#ua#e has #one from bein# mostly Western to attractin# -ro#rammers from all over the world! Language standard ,n 1==(6 the C?? standards committee @the ,S1&,EC J+C1&SC22&W21 wor5in# #rou-A standardi8ed C?? and -ublished the international standard ,S1&,EC 1'((221==( @informally 5nown as C??=(V'WA! 7or some years after the official release of the standard6 the committee -rocessed defect re-orts6 and -ublished a corrected version of the C?? standard6 ,S1&,EC 1'((2220036 in 2003! ,n 200;6 a technical re-ort6 called the GEibrary +echnical "e-ort 1G @often 5nown as +"1 for shortA6 was released! While not an official -art of the standard6 it s-ecified a number of e0tensions to the standard library6 which were e0-ected to be included in the ne0t version of C??! Su--ort for +"1 is #rowin# in almost all currently maintained C?? com-ilers! While the C?? lan#ua#e is royalty>free6 the standard document itself is not freely available! Etymology .ccordin# to Stroustru-2 Gthe name si#nifies the evolutionary nature of the chan#es from CG! )urin# C??Rs develo-ment -eriod6 the lan#ua#e had been referred to as Gnew CG6 then GC with ClassesG! +he final name is credited to "ic5 :ascitti @mid>1=(3A and was first used in )ecember 1=(3! When :ascitti was 4uestioned informally in 1==2 about the namin#6 he indicated that it was #iven in a ton#ue>in>chee5 s-irit! ,t stems from CRs G??G o-erator @which increments the value of a variableA and a common namin# convention of usin# G?G to indicate an enhanced com-uter -ro#ram! +here is no lan#ua#e called GC -lusG! .<CE&c? was the name of an earlier6 unrelated -ro#rammin# lan#ua#e! 20 !ilosop!y ,n +he )esi#n and Evolution of C?? @1=='A6 </arne Stroustru- describes some rules that he uses for the desi#n of C??2 C?? is desi#ned to be a statically ty-ed6 #eneral>-ur-ose lan#ua#e that is as efficient and -ortable as C!
C?? is desi#ned to directly and com-rehensively su--ort multi-le -ro#rammin# styles @-rocedural -ro#rammin#6 data abstraction6 ob/ect>oriented -ro#rammin#6 and #eneric -ro#rammin#A C?? is desi#ned to #ive the -ro#rammer choice6 even if this ma5es it -ossible for the -ro#rammer to choose incorrectly C?? is desi#ned to be as com-atible with C as -ossible6 therefore -rovidin# a smooth transition from C C?? avoids features that are -latform s-ecific or not #eneral -ur-ose C?? does not incur overhead for features that are not used @the G8ero>overhead -rinci-leGA C?? is desi#ned to function without a so-histicated -ro#rammin# environment ,nside the C?? 1b/ect :odel @Ei--man6 1==CA describes how com-ilers may convert C? ? -ro#ram statements into an in>memory layout! Com-iler authors are6 however6 free to im-lement the standard in their own manner! Standard library +he 1==( .$S,&,S1 C?? standard consists of two -arts2 the core lan#ua#e and the C?? Standard EibraryN the latter includes most of the Standard +em-late Eibrary @S+EA and a 21 sli#htly modified version of the C standard library! :any C?? libraries e0ist which are not -art of the standard6 and6 usin# lin5a#e s-ecification6 libraries can even be written in lan#ua#es such as C6 7ortran6 3ascal6 or <.S,C! Which of these are su--orted is com-iler de-endent! +he C?? standard library incor-orates the C standard library with some small modifications to ma5e it o-timi8ed with the C?? lan#ua#e! .nother lar#e -art of the C?? library is based on the S+E! +his -rovides such useful tools as containers @for e0am-le vectors and listsA6 iterators to -rovide these containers with array>li5e access and al#orithms to -erform o-erations such as searchin# and sortin#! 7urthermore @multiAma-s @associative arraysA and @multiAsets are -rovided6 all of which e0-ort com-atible interfaces! +herefore it is -ossible6 usin# tem-lates6 to write #eneric al#orithms that wor5 with any container or on any se4uence defined by iterators! .s in C6 the features of the library are accessed by usin# the Binclude directive to include a standard header! C?? -rovides C= standard headers6 of which 1= are de-recated! +he S+E was ori#inally a third>-arty library from D3 and later S,6 before its incor-oration into the C?? standard! +he standard does not refer to it as GS+EG6 as it is merely a -art of the standard library6 but many -eo-le still use that term to distin#uish it from the rest of the library @in-ut&out-ut streams6 internationali8ation6 dia#nostics6 the C library subset6 etc!A! :ost C?? com-ilers -rovide an im-lementation of the C?? standard library6 includin# the S+E! Com-iler>inde-endent im-lementations of the S+E6 such as S+E3ort6 also e0ist! 1ther -ro/ects also -roduce various custom im-lementations of the C?? standard library and the S+E with various desi#n #oals! Language features C?? inherits most of CRs synta0 and the C -re-rocessor! +he followin# is </arne Stroustru-Rs versionRs of the Dello world -ro#ram which uses the C?? standard library stream facility to write a messa#e to standard out-ut2 22 Binclude PiostreamQ
int main@A X std22cout PP GDello6 worldJSnGN Y "perators and operator o#erloading C?? -rovides more than 30 o-erators6 coverin# basic arithmetic6 bit mani-ulation6 indirection6 com-arisons6 lo#ical o-erations and more! .lmost all o-erators can be overloaded for user>defined ty-es6 with a few notable e0ce-tions such as member access @! and !OA! +he rich set of overloadable o-erators is central to usin# C?? as a domain s-ecific lan#ua#e! +he overloadable o-erators are also an essential -art of many advanced C?? -ro#rammin# techni4ues6 such as smart -ointers! 1verloadin# an o-erator does not chan#e the -recedence of calculations involvin# the o-erator6 nor does it chan#e the number of o-erands that the o-erator uses @any o-erand may however be i#noredA! Templates C?? tem-lates enable #eneric -ro#rammin#! C?? su--orts both function and class tem-lates! +em-lates may be -arameteri8ed by ty-es6 com-ile>time constants6 and other tem-lates! C?? tem-lates are im-lemented by instantiation at com-ile>time! +o instantiate a tem-late6 com-ilers substitute s-ecific ar#uments for a tem-lateRs -arameters to #enerate a concrete function or class instance! +em-lates are a -owerful tool that can be used for #eneric -ro#rammin#6 tem-late meta-ro#rammin#6 and code o-timi8ation6 but this -ower im-lies a cost! +em-late use may increase code si8e6 since each tem-late instantiation -roduces a co-y of the tem-late code2 one for each set of tem-late ar#uments! +his is in contrast to run>time #enerics seen in other lan#ua#es @e!#! JavaA where at com-ile>time the ty-e is erased and a sin#le tem-late body is -reserved! 23 +em-lates are different from macros2 while both of these com-ile>time lan#ua#e features enable conditional com-ilation6 tem-lates are not restricted to le0ical substitution! +em-lates are aware of the semantics and ty-e system of their com-anion lan#ua#e6 as well as all com-ile>time ty-e definitions6 and can -erform hi#h>level o-erations includin# -ro#rammatic flow control based on evaluation of strictly ty-e>chec5ed -arameters! :acros are ca-able of conditional control over com-ilation based on -redetermined criteria6 but cannot instantiate new ty-es6 recurse6 or -erform ty-e evaluation and in effect are limited to -re>com-ilation te0t>substitution and te0t>inclusion&e0clusion! ,n other words6 macros can control com-ilation flow based on -re>defined symbols but cannot6 unli5e tem-lates6 inde-endently instantiate new symbols! +em-lates are a tool for static -olymor-hism @see belowA and #eneric -ro#rammin#! ,n addition6 tem-lates are a com-ile time mechanism in C?? which is +urin#>com-lete6 meanin# that any com-utation e0-ressible by a com-uter -ro#ram can be com-uted6 in some form6 by a tem-late meta-ro#ram -rior to runtime! ,n summary6 a tem-late is a com-ile>time -arameteri8ed function or class written without 5nowled#e of the s-ecific ar#uments used to instantiate it! .fter instantiation the resultin# code is e4uivalent to code written s-ecifically for the -assed ar#uments! ,n this manner6 tem-lates -rovide a way to decou-le #eneric6 broadly>a--licable as-ects of functions and classes @encoded in tem-latesA from s-ecific as-ects @encoded in tem-late -arametersA without sacrificin# -erformance due to abstraction! "b$ects C?? introduces ob/ect>oriented @11A features to C! ,t offers classes6 which -rovide the four features commonly -resent in 11 @and some non>11A lan#ua#es2 abstraction6 enca-sulation6 inheritance6 and -olymor-hism! 1b/ects are instances of classes created at runtime! +he class can be thou#ht of as a tem-late from which many different individual ob/ects may be #enerated as a -ro#ram runs! 2' Encapsulation Enca-sulation is the hidin# of information in order to ensure that data structures and o-erators are used as intended and to ma5e the usa#e model more obvious to the develo-er! C?? -rovides the ability to define classes and functions as its -rimary enca-sulation mechanisms! Within a class6 members can be declared as either -ublic6 -rotected6 or -rivate in order to e0-licitly enforce enca-sulation! . -ublic member of the class is accessible to any function! . -rivate member is accessible only to functions that are members of that class and to functions and classes e0-licitly #ranted access -ermission by the class @GfriendsGA! . -rotected member is accessible to members of classes that inherit from the class in addition to the class itself and any friends! +he 11 -rinci-le is that all of the functions @and only the functionsA that access the internal re-resentation of a ty-e should be enca-sulated within the ty-e definition! C?? su--orts this @via member functions and friend functionsA6 but does not enforce it2 the -ro#rammer can declare -arts or all of the re-resentation of a ty-e to be -ublic6 and is allowed to ma5e -ublic entities that are not -art of the re-resentation of the ty-e! <ecause of this6 C?? su--orts not /ust 11 -ro#rammin#6 but other wea5er decom-osition -aradi#ms6 li5e modular -ro#rammin#! ,t is #enerally considered #ood -ractice to ma5e all data -rivate or -rotected6 and to ma5e -ublic only those functions that are -art of a minimal interface for users of the class! +his hides all the details of data im-lementation6 allowin# the desi#ner to later fundamentally chan#e the im-lementation without chan#in# the interface in any way!V(WV=W %n!eritance ,nheritance allows one data ty-e to ac4uire -ro-erties of other data ty-es! ,nheritance from a base class may be declared as -ublic6 -rotected6 or -rivate! +his access s-ecifier determines whether unrelated and derived classes can access the inherited -ublic and -rotected members of the base class! 1nly -ublic inheritance corres-onds to what is usually meant by GinheritanceG! +he other two forms are much less fre4uently used! ,f the access s-ecifier is omitted6 a GclassG inherits -rivately6 while a GstructG inherits -ublicly! 2; <ase classes may be declared as virtualN this is called virtual inheritance! %irtual inheritance ensures that only one instance of a base class e0ists in the inheritance #ra-h6 avoidin# some of the ambi#uity -roblems of multi-le inheritance! :ulti-le inheritance is a C?? feature sometimes considered controversial! :ulti-le inheritance allows a class to be derived from more than one base classN this can result in a com-licated #ra-h of inheritance relationshi-s! 7or e0am-le6 a G7lyin# CatG class can inherit from both GCatG and G7lyin# :ammalG! Some other lan#ua#es6 such as Java or CB6 accom-lish somethin# similar @althou#h more limitedA by allowin# inheritance of multi-le interfaces while restrictin# the number of base classes to one @interfaces6 unli5e classes6 -rovide only declarations of member functions6 no im-lementation or member dataA! ,nterfaces and abstract classes in Java and CB can be e0-ressed in C?? as a class containin# only function declarations6 often 5nown as an abstract base class or G.<C!G 3ro#rammers -referrin# the Java&CB model of inheritance can choose to inherit only one non>abstract class6 and can otherwise limit themselves to only abstract classes! olymorp!ism See also2 3olymor-hism in ob/ect>oriented -ro#rammin# 3olymor-hism enables one common interface for many im-lementations6 and for ob/ects to act differently under different circumstances! C?? su--orts several 5inds of static @com-ile>timeA and dynamic @run>timeA -olymor-hisms! Com-ile>time -olymor-hism does not allow for certain run>time decisions6 while run>time -olymor-hism ty-ically incurs a -erformance -enalty! Static polymorp!ism 7unction overloadin# allows -ro#rams to declare multi-le functions havin# the same name @but with different ar#umentsA! +he functions are distin#uished by the number and&or ty-es of their formal -arameters! +hus6 the same function name can refer to different functions de-endin# on the conte0t in which it is used! +he ty-e returned by the function is not used to distin#uish overloaded functions! 2C When declarin# a function6 a -ro#rammer can s-ecify default ar#uments for one or more -arameters! )oin# so allows the -arameters with defaults to o-tionally be omitted when the function is called6 in which case the default ar#uments will be used! When a function is called with fewer ar#uments than there are declared -arameters6 e0-licit ar#uments are matched to -arameters in left>to>ri#ht order6 with any unmatched -arameters at the end of the -arameter list bein# assi#ned their default ar#uments! ,n many cases6 s-ecifyin# default ar#uments in a sin#le function declaration is -referable to -rovidin# overloaded function definitions with different numbers of -arameters! +em-lates in C?? -rovide a so-histicated mechanism for writin# #eneric6 -olymor-hic code! ,n -articular6 throu#h the Curiously "ecurrin# +em-late 3attern itRs -ossible to im-lement a form of static -olymor-hism that closely mimics the synta0 for overridin# virtual functions! Since C?? tem-lates are ty-e>aware and +urin#>com-lete they can also be used to let the com-iler resolve recursive conditionals and #enerate substantial -ro#rams throu#h tem-late meta-ro#rammin#! &ynamic polymorp!ism %n!eritance %ariable -ointers @and referencesA to a base class ty-e in C?? can refer to ob/ects of any derived classes of that ty-e in addition to ob/ects e0actly matchin# the variable ty-e! +his allows arrays and other 5inds of containers to hold -ointers to ob/ects of differin# ty-es! <ecause assi#nment of values to variables usually occurs at run>time6 this is necessarily a run>time -henomenon! C?? also -rovides a dynamic\cast o-erator6 which allows the -ro#ram to safely attem-t conversion of an ob/ect into an ob/ect of a more s-ecific ob/ect ty-e @as o--osed to conversion to a more #eneral ty-e6 which is always allowedA! +his feature relies on run> time ty-e information @"++,A! 1b/ects 5nown to be of a certain s-ecific ty-e can also be cast to that ty-e with static\cast6 a -urely com-ile>time construct which is faster and does not re4uire "++,! 2* 'irtual member functions 1rdinarily when a function in a derived class overrides a function in a base class6 the function to call is determined by the ty-e of the ob/ect! . #iven function is overridden when there e0ists no difference6 in the number or ty-e of -arameters6 between two or more definitions of that function! Dence6 at com-ile time it may not be -ossible to determine the ty-e of the ob/ect and therefore the correct function to call6 #iven only a base class -ointerN the decision is therefore -ut off until runtime! +his is called dynamic dis-atch! %irtual member functions or methods allow the most s-ecific im-lementation of the function to be called6 accordin# to the actual run>time ty-e of the ob/ect! ,n C??6 this is commonly done usin# virtual function tables! ,f the ob/ect ty-e is 5nown6 this may be by-assed by -re-endin# a fully 4ualified class name before the function call6 but in #eneral calls to virtual functions are resolved at run time! ,n addition to standard member functions6 o-erator overloads and destructors can be virtual! . #eneral rule of thumb is that if any functions in the class are virtual6 the destructor should be as well! .s the ty-e of an ob/ect at its creation is 5nown at com-ile time6 constructors6 and by e0tension co-y constructors6 cannot be virtual! $onetheless a situation may arise where a co-y of an ob/ect needs to be created when a -ointer to a derived ob/ect is -assed as a -ointer to a base ob/ect! ,n such a case a common solution is to create a clone@A @or similarA function and declare that as virtual! +he clone@A method creates and returns a co-y of the derived class when called! . member function can also be made G-ure virtualG by a--endin# it with M 0 after the closin# -arenthesis and before the semicolon! 1b/ects cannot be created of a class with a -ure virtual function and are called abstract data ty-es! Such abstract data ty-es can only be derived from! .ny derived class inherits the virtual function as -ure and must -rovide a non>-ure definition of it @and all other -ure virtual functionsA before ob/ects of the derived class can be created! .n attem-t to create an ob/ect from a class with a -ure virtual function or inherited -ure virtual function will be fla##ed as a com-ile>time error! 2( arsing and processing C(( source code ,t is relatively difficult to write a #ood C?? -arser with classic -arsin# al#orithms such as E.E"@1A! +his is -artly because the C?? #rammar is not E.E"! <ecause of this6 there are very few tools for analy8in# or -erformin# non>trivial transformations @e!#!6 refactorin#A of e0istin# code! 1ne way to handle this difficulty is to choose a different synta06 such as Si#nificantly 3rettier and Easier C?? Synta06 which is E.E"@1A -arsable! :ore -owerful -arsers6 such as E" -arsers6 can be substantially sim-ler @thou#h slowerA! 3arsin# @in the literal sense of -roducin# a synta0 treeA is not the most difficult -roblem in buildin# a C?? -rocessin# tool! Such tools must also have the same understandin# of the meanin# of the identifiers in the -ro#ram as a com-iler mi#ht have! 3ractical systems for -rocessin# C?? must then not only -arse the source te0t6 but be able to resolve for each identifier -recisely which definition a--lies @e!#! they must correctly handle C??Rs com-le0 sco-in# rulesA and what its ty-e is6 as well as the ty-es of lar#er e0-ressions! 7inally6 a -ractical C?? -rocessin# tool must be able to handle the variety of C?? dialects used in -ractice @such as that su--orted by the $9 Com-iler Collection and that of :icrosoftRs %isual C??A and im-lement a--ro-riate analy8ers6 source code transformers6 and re#enerate source te0t! Combinin# advanced -arsin# al#orithms such as E" with symbol table construction and -ro#ram transformation machinery can enable the construction of arbitrary C?? tools! Compatibility 3roducin# a reasonably standards>com-liant C?? com-iler has -roven to be a difficult tas5 for com-iler vendors in #eneral! 7or many years6 different C?? com-ilers im-lemented the C?? lan#ua#e to different levels of com-liance to the standard6 and their im-lementations varied widely in some areas such as -artial tem-late s-eciali8ation! "ecent releases of most -o-ular C?? com-ilers su--ort almost all of the C?? 1==( standard! .--arently there is no im-lementation that fully su--orts the entire standard! 2= 1ne -articular -oint of contention is the e0-ort 5eyword6 intended to allow tem-late definitions to be se-arated from their declarations! +he first com-iler to im-lement e0-ort was Comeau C&C??6 in early 2003 @; years after the release of the standardAN in 200'6 the beta com-iler of <orland C?? <uilder F was also released with e0-ort! <oth of these com-ilers are based on the E) C?? front end! ,t should also be noted that many C?? boo5s -rovide e0am-le code usin# the 5eyword e0-ort @for e0am-le6 <e#innin# .$S, C? ? by ,vor DortonA which will not com-ile in most com-ilers6 but there is no reference to the -roblem with the 5eyword e0-ort mentioned! 1ther com-ilers such as CC do not su--ort it at all! Derb Sutter6 former convener of the C?? standards committee6 recommended that e0-ort be removed from future versions of the C?? standard6 but finally the decision was made to retain it! ,n order to #ive com-iler vendors #reater freedom6 the C?? standards committee decided not to dictate the im-lementation of name man#lin#6 e0ce-tion handlin#6 and other im-lementation>s-ecific features! +he downside of this decision is that ob/ect code -roduced by different com-ilers is e0-ected to be incom-atible! +here are6 however6 third -arty standards for -articular machines or o-eratin# systems which attem-t to standardi8e com-ilers on those -latforms @for e0am-le C?? .<,V1;WAN some com-ilers ado-t a secondary standard for these items! )it! C 7or more details on this to-ic6 see Com-atibility of C and C??! C?? is often considered to be a su-erset of C6 but this is not strictly true!V1CW :ost C code can easily be made to com-ile correctly in C??6 but there are a few differences that cause some valid C code to be invalid in C??6 or to behave differently in C??! 1ne commonly encountered difference is that C allows im-licit conversion from voidO to other -ointer ty-es6 but C?? does not! .nother common -ortability issue is that C?? defines many new 5eywords6 such as new and class6 that may be used as identifiers @e!#! variable namesA in a C -ro#ram! 30 Some incom-atibilities have been removed by the latest @C==A C standard6 which now su--orts C?? features such as && comments and mi0ed declarations and code! 1n the other hand6 C== introduced a number of new features that C?? does not su--ort6 such as variable>len#th arrays6 native com-le0>number ty-es6 desi#nated initiali8ers and com-ound literals! Dowever6 at least some of the new C== features will li5ely be included in the ne0t version of the C?? standard6 C??00! ,n order to intermi0 C and C?? code6 any function declaration or definition that is to be called from&used both in C and C?? must be declared with C lin5a#e by -lacin# it within an e0tern GCG X !!! Y bloc5! Such a function may not rely on features de-endin# on name man#lin# @i!e!6 function overloadin#A! 31 .. PRO*RAMMIN* IN C++ %*T+"&,CT%"* T" C(( C?? is lan#ua#e develo-ed to su--ort modern 113Is6 while at the same time retainin# the loo5 of already e0istin# and 4uite -o-ular lan#ua#e ZCI! +his section -rovides an overview of the 5ey conce-ts embodied in C??! ,ts ob/ect oriented features are hi#hly interrelated! 1n several instances one feature im-lies -rior 5nowled#e of one or more features! +his section #ives a 4uic5 overview of most im-ortant as-ects of C??! "+%-%* "F C(( C?? is an e0-anded version of C! +he C?? e0tension to C were first invented by <.J."$E S+"19S+"93 in 1=(0 at <ell labs !.lthou#h C ??Is -redecessor is one of most li5ed and widely used -rofessional -ro#rammin# factors increasin# com-le0ity! 1ver the years com-uters -ro#rams has become lar#e and com-le0!ity !essence of C?? is to allow -ro#rammer to com-rehend and mana#e lar#er and com-le0 -ro#ram! When C?? was invented6 STROUSTRUP 5new that it was im-ortant to maintain ori#inal s-rit of C6 includin# its efficiency6 its fle0ibility and under lyin# -hiloso-hy that the -ro#rams6 not the lan#ua#e6 is in chan#e while at the same time addin# su--ort for 113Is! Da--ily6 his #oals were accom-lished !C?? still -rovides the -ro#rammer with the freedom and control of C?? still -rovides the -ro#rammer with the freedom and control of C cou-led with the -ower of ob/ect! )./T %S ""S0
1b/ect 1riented 3ro#rammin# @113A is a new way of a--roachin# the /ob of the -ro#rams! .--roaches to -ro#rammin# have chan#ed dramatically since the invention of com-uter6 -rimarily to accommodate the increasin# com-le0ity of -ro#rams! 7or e0am-le 6the -ro#rammin# a--roach evolved from the machine lan#ua#e -ro#rammin# involves DEEs @hi#h level lan#ua#e A! Certain hi#hli#hts of structured -ro#rammin# are2 32 1A em-hasis on doin# thin#s rather than data! 2A Ear#e -ro#ram divided into smaller -ro#rams 5nown as functions! 3A )ata is shared fre4uently ! 'A )ata moves o-enly around the system from function to function! ;A 7unction can transform data one from to another! 113 has ta5en the best ideas of structured -ro#rammin# and combined with several -owerful conce-ts that encoura#es you to a--roach the tas5 of -ro#rammin# in a new way! When -ro#rammin# in a ob/ect oriented manner 6a -roblem is bro5en down into sub#rou-s of the related -arts that ta5e into account both code and data related to each #rou-! .lso these sub#rou-s are or#ani8ed into a hierarchical structure! 7inally these sub#rou-s are translated into self>contained units called ob/ects! .ll ob/ects oriented -ro#rammin# lan#ua#es have three traits in common2 Enca-sulation6 -olymor-hism and inheritance ! Eet us e0amine these briefly! C++ at a *"ance Some of im-ortant features or im-ortant -arts of C?? ! 1A 9nli5e C6C?? is a stron#ly ty-ed lan#ua#e 2 Every ob/ect must belon# to a ty-e and an ob/ect of one ty-e cannot be assi#ned to or com-ared with one of the another ty-es by well defined conversion! 2A 7unction -rototy-e is mandatory in C??! 3A Call by reference is su--orted in C??! +his removes one of the difficult -ointer code sometimes found in C code ! . direct result is that any lar#e structure should be -assed by reference! 'A +he com-iler directive const can be used in many -laces to im-ly that some ob/ects is unalterable ! +his is manifested in no ! of ways! 7irst lar#e structure can be safely -assed as const and by reference 6 rather than usin# a -ointer ! Second 33 even inte#ers that are -assed by value can be s-ecified as const to -revent accidental modification! .-art from the above characteristics6 s-ecific constructs that are offered by C?? are discussed later on! Classes . class in C?? is collection of some data fields and the functions mani-ulatin# them ! . class may contain -ublic as well -rivate -arts !<y default6 all the items defined in a class are -rivate !+his means that they cannot be accessed by any function that is not a member of the class !+his is one way that enca-sulation has been achieved ] access to certain items of data can be ti#htly controlled by 5ee-in# them -rivate! +o ma5es -arts of a class -ublic 6 these must be declared after the -ublic 5eyword !.ll variables or function defined after -ublic can be accessed by other function in the -ro#ram ! Essentially 6 the rest of your -ro#ram access an ob/ect throu#h its -ublic function! "'E+L"/&%*- C?? achieves -olymor-hism throu#h the use of overloadin# ! ,n C?? overloadin# is of two ty-es 2 7unctional overloadin# and o-erator overloadin#! ,t is allowed in C?? that two or more function share name as lon# as their -arameter declaration are different ! ,n this situation the function that shares the same name said to be overloaded and this -rocess is referred to as function overloadin# ! When a function call is made the com-iler determines which of the identical names are bein# referred to!
Closely related to functional overloadin# there is o-erator overloadin# !,n C??6 you can overload most o-erators so that they can -erform s-ecial o-erations relative to classes 3' that you create! 7or e0am-le a class that maintains a stac5 mi#ht overload ?? to -erform -ush u- o-eration and ] to -erform a -o-! When an o-erator is overloaded none of its ori#inal meanin# are lost ! ,nstead the ty-e of ob/ects it can be a--lied to is e0-anded! 1-erator overloadin# is achieved by creatin# o-erator function! .n o-erator function defines o-erations that the overloaded o-erator will -erform relative to the class it is desi#ned to wor5 on! C"*ST+,CT%"+S /*& &EST+,CT%"*S ,t is very common form some -art of an ob/ect to re4uire initiali8ation before it can be used ! <ecause of the re4uirements for initiali8ation is so common 6C?? allows ob/ects to initiali8e themselves when they are created !+he automatic initiali8ation is -erformed throu#h the use of constructor function !. constructor function is a s-ecial function that is a member of a class and has the same name as that of the class !.s the ob/ectI s constructor is automatically called when the ob/ect is created ! +his means that it is called when the ob/ectIs declaration is e0ecuted! +he com-lement of the constructor is destructor ! ,n many circumstances an ob/ect will need to -erform some action or actions when it is destroyed !7or e0am-le closin# of an o-ened file deallocation of memory etc ! ,n C?? it is the destructor function that handles deactivation events! +he destructor has the same name as that of the constructor6 but it is -receded by> @tildeA symbol! +"-+/11%*- 3ro#rammin# is the course of desi#nin# 6writin#6 testin# and maintainin# that ma5es the com-uter wor5s accordin# to our re4uirements! +his section e0-lains how efficient -ro#rammin# can be achieved! 3; W%at i# a Progra./
1A . -lan to achieve a -roblem solution N 2A +o desi#n6 write and test one or more routines N 3A . set of se4uenced instructions to cause a com-uter to -erform -articular o-eration! ,o0 to 0rite a C++ Progra / 3ro#rams are not 4uic5 creations ! "ather a series of ste-s that are to be wor5ed out 6 which are bein# ta5en by the command lines! Ste! 1 .De1ine t%e need 2> +o create a new -ro#ram or to im-rove or to modify an e0istin# one 6 first reco#ni8e that -roblem ! 9nder this ste- the -ro#rammer must have a clear understandin# of e0actly what is that to be done T Ste! 2. Ana"23e 2> +his ste- is basically concerned with the decom-osition of a -roblem into the com-onents -arts and establishin# a lo#ical model to describe the system functions ! 7ollowin# are the sub>ste-s constitute this ste- !
1A ,dentifyin# the ob/ects and their attributes! 2A ,dentifyin# the service that each ob/ect is e0-ected to -rovide! 3A Establishin# inter ]connection between ob/ects in terms of service re4uired and services rendered! Ste! $.De#ign 2> 9nder this ste- followin# actions ta5e -lace2
aA S-ecifications of the class de-endencies! bA 1r#ani8ation of the class hierarchies! cA )esi#n of classes ! dA )esi#n of member functions ! eA )esi#n of the driver -ro#ram ! 3C Every C?? -ro#ram must ain45 function code 5nown as dri6e !rogra ! +he e0ecution of the -ro#ram be#ins and ends here! +he drive -ro#ram is mainly res-onsible for N
aA "eceivin# data values from the userN bA Creatin# ob/ects from class definitionsN cA Establishin# communication between ob/ectsN dA )is-layin# & -roducin# the out-ut results in the form re4uired by the user! ,n nutshell6 the driver -ro#ram is #ateway to the users! Ste! ). I!"eent :7+his includes codin# and testin# ! Codin# includes writin# codes for classes and member function and the ain -ro#ram which acts as a driver in the -ro#ram ! +o develo- the lo#ic of the functions6 -ro#ram develo-ment tools may be used! $o -ro#ram wor5s accurately for the first time ! So testin# the -ro#ram before usin# is an essential -art of the -ro#rammin# !+he final #oal of testin# is to see that the -ro#ram the intended /ob satisfactorily!
3* 8. Str&ct&re o1 a !rogra 3robably the best way to start learnin# a -ro#rammin# lan#ua#e is by writin# a -ro#ram! +herefore6 here is our first -ro#ram2 && my first -ro#ram in C?? Binclude PiostreamQ usin# names-ace stdN int main @A X cout PP GDello WorldJGN return 0N Y Dello WorldJ +he first -anel shows the source code for our first -ro#ram! +he second one shows the result of the -ro#ram once com-iled and e0ecuted! +he way to edit and com-ile a -ro#ram de-ends on the com-iler you are usin#! )e-endin# on whether it has a )evelo-ment ,nterface or not and on its version! Consult the com-ilers section and the manual or hel- included with your com-iler if you have doubts on how to com-ile a C?? console -ro#ram! +he -revious -ro#ram is the ty-ical -ro#ram that -ro#rammer a--rentices write for the first time6 and its result is the -rintin# on screen of the GDello WorldJG sentence! ,t is one of the sim-lest -ro#rams that can be written in C??6 but it already contains the fundamental com-onents that every C?? -ro#ram has! We are #oin# to loo5 line by line at the code we have /ust written2 99 2 1ir#t !rogra in C++ 3( +his is a comment line! .ll lines be#innin# with two slash si#ns @&&A are considered comments and do not have any effect on the behavior of the -ro#ram! +he -ro#rammer can use them to include short e0-lanations or observations within the source code itself! ,n this case6 the line is a brief descri-tion of what our -ro#ram is! :inc"&de ;io#trea< Eines be#innin# with a hash si#n @BA are directives for the -re-rocessor! +hey are not re#ular code lines with e0-ressions but indications for the com-ilerRs -re-rocessor! ,n this case the directive Binclude PiostreamQ tells the -re-rocessor to include the iostream standard file! +his s-ecific file @iostreamA includes the declarations of the basic standard in-ut>out-ut library in C??6 and it is included because its functionality is #oin# to be used later in the -ro#ram! &#ing nae#!ace #td= .ll the elements of the standard C?? library are declared within what is called a names-ace6 the names-ace with the name std! So in order to access its functionality we declare with this e0-ression that we will be usin# these entities! +his line is very fre4uent in C?? -ro#rams that use the standard library6 and in fact it will be included in most of the source codes included in these tutorials! int ain 45 +his line corres-onds to the be#innin# of the definition of the main function! +he main function is the -oint by where all C?? -ro#rams start their e0ecution6 inde-endently of its location within the source code! ,t does not matter whether there are other functions with other names defined before or after it > the instructions contained within this functionRs definition will always be the first ones to be e0ecuted in any C?? -ro#ram! 7or that same reason6 it is essential that all C?? -ro#rams have a main function! +he word main is followed in the code by a -air of -arentheses @@AA! +hat is because it is a function declaration2 ,n C??6 what differentiates a function 3= declaration from other ty-es of e0-ressions are these -arentheses that follow its name! 1-tionally6 these -arentheses may enclose a list of -arameters within them! "i#ht after these -arentheses we can find the body of the main function enclosed in braces @XYA! What is contained within these braces is what the function does when it is e0ecuted! co&t ;; >,e""o Wor"d>= +his line is a C?? statement! . statement is a sim-le or com-ound e0-ression that can actually -roduce some effect! ,n fact6 this statement -erforms the only action that #enerates a visible effect in our first -ro#ram! cout re-resents the standard out-ut stream in C??6 and the meanin# of the entire statement is to insert a se4uence of characters @in this case the Dello World se4uence of charactersA into the standard out-ut stream @which usually is the screenA! cout is declared in the iostream standard file within the std names-ace6 so thatRs why we needed to include that s-ecific file and to declare that we were #oin# to use this s-ecific names-ace earlier in our code! $otice that the statement ends with a semicolon character @NA! +his character is used to mar5 the end of the statement and in fact it must be included at the end of all e0-ression statements in all C?? -ro#rams @one of the most common synta0 errors is indeed to for#et to include some semicolon after a statementA! ?aria@"e#. Data T2!e#. +he usefulness of the GDello WorldG -ro#rams shown in the -revious section is 4uite 4uestionable! We had to write several lines of code6 com-ile them6 and then e0ecute the resultin# -ro#ram /ust to obtain a sim-le sentence written on the screen as result! ,t certainly would have been much faster to ty-e the out-ut sentence by ourselves! Dowever6 -ro#rammin# is not limited only to -rintin# sim-le te0ts on the screen! ,n order '0 to #o a little further on and to become able to write -ro#rams that -erform useful tas5s that really save us wor5 we need to introduce the conce-t of variable! Eet us thin5 that , as5 you to retain the number ; in your mental memory6 and then , as5 you to memori8e also the number 2 at the same time! Hou have /ust stored two different values in your memory! $ow6 if , as5 you to add 1 to the first number , said6 you should be retainin# the numbers C @that is ;?1A and 2 in your memory! %alues that we could now for e0am-le subtract and obtain ' as result! +he whole -rocess that you have /ust done with your mental memory is a simile of what a com-uter can do with two variables! +he same -rocess can be e0-ressed in C?? with the followin# instruction set2 a M ;N b M 2N a M a ? 1N result M a > bN 1bviously6 this is a very sim-le e0am-le since we have only used two small inte#er values6 but consider that your com-uter can store millions of numbers li5e these at the same time and conduct so-histicated mathematical o-erations with them! +herefore6 we can define a variable as a -ortion of memory to store a determined value! Each variable needs an identifier that distin#uishes it from the others6 for e0am-le6 in the -revious code the variable identifiers were a6 b and result6 but we could have called the variables any names we wanted to invent6 as lon# as they were valid identifiers! Dec"aration o1 6aria@"e# ,n order to use a variable in C??6 we must first declare it s-ecifyin# which data ty-e we want it to be! +he synta0 to declare a new variable is to write the s-ecifier of the desired data ty-e @li5e int6 bool6 float!!!A followed by a valid variable identifier! 7or e0am-le2 '1 int aN float mynumberN +hese are two valid declarations of variables! +he first one declares a variable of ty-e int with the identifier a! +he second one declares a variable of ty-e float with the identifier mynumber! 1nce declared6 the variables a and mynumber can be used within the rest of their sco-e in the -ro#ram! ,f you are #oin# to declare more than one variable of the same ty-e6 you can declare all of them in a sin#le statement by se-aratin# their identifiers with commas! 7or e0am-le2 int a6 b6 cN +his declares three variables @a6 b and cA6 all of them of ty-e int6 and has e0actly the same meanin# as2 int aN int bN int cN Introd&ction to #tring# %ariables that can store non>numerical values that are lon#er than one sin#le character are 5nown as strin#s! +he C?? lan#ua#e library -rovides su--ort for strin#s throu#h the standard strin# class! +his is not a fundamental ty-e6 but it behaves in a similar way as fundamental ty-es do in its most basic usa#e! . first difference with fundamental data ty-es is that in order to declare and use ob/ects @variablesA of this ty-e we need to include an additional header file in our source code2 Pstrin#Q and have access to the std names-ace @which we already had in all our -revious -ro#rams than5s to the usin# names-ace statementA! '2 && my first strin# Binclude PiostreamQ Binclude Pstrin#Q usin# names-ace stdN int main @A X strin# mystrin# M G+his is a strin#GN cout PP mystrin#N return 0N Y O!erator# 1nce we 5now of the e0istence of variables and constants6 we can be#in to o-erate with them! 7or that -ur-ose6 C?? inte#rates o-erators! 9nli5e other lan#ua#es whose o-erators are mainly 5eywords6 o-erators in C?? are mostly made of si#ns that are not -art of the al-habet but are available in all 5eyboards! +his ma5es C?? code shorter and more international6 since it relies less on En#lish words6 but re4uires a little of learnin# effort in the be#innin#! Hou do not have to memori8e all the content of this -a#e! :ost details are only -rovided to serve as a later reference in case you need it! A##ignent 4A5 +he assi#nment o-erator assi#ns a value to a variable! a M ;N Arit%etic o!erator# 4 +B 7B CB 9B D 5 +he five arithmetical o-erations su--orted by the C?? lan#ua#e are2 '3 ? addition > subtraction O multi-lication & division [ modulo Re"ationa" and eE&a"it2 o!erator# 4 AAB FAB <B ;B <AB ;A 5 ,n order to evaluate a com-arison between two e0-ressions we can use the relational and e4uality o-erators! +he result of a relational o-eration is a <oolean value that can only be true or false6 accordin# to its <oolean result! We may want to com-are two e0-ressions6 for e0am-le6 to 5now if they are e4ual or if one is #reater than the other is! Dere is a list of the relational and e4uality o-erators that can be used in C??2 MM E4ual to JM $ot e4ual to Q reater than P Eess than QM reater than or e4ual to PM Eess than or e4ual to (ogica" o!erator# 4 FB GGB HH 5 +he 1-erator J is the C?? o-erator to -erform the <oolean o-eration $1+6 it has only one o-erand6 located at its ri#ht6 and the only thin# that it does is to inverse the value of '' it6 -roducin# false if its o-erand is true and true if its o-erand is false! <asically6 it returns the o--osite <oolean value of evaluatin# its o-erand! 7or e0am-le2 J@; MM ;A && evaluates to false because the e0-ression at its ri#ht @; MM ;A is true! J@C PM 'A && evaluates to true because @C PM 'A would be false! Jtrue && evaluates to false Jfalse && evaluates to true! +he lo#ical o-erators && and ^^ are used when evaluatin# two e0-ressions to obtain a sin#le relational result! +he o-erator && corres-onds with <oolean lo#ical o-eration .$)! +his o-eration results true if both its two o-erands are true6 and false otherwise! +he followin# -anel shows the result of o-erator && evaluatin# the e0-ression a && b! '; CONC(USION Saraswati Com-uter Centre is the leadin# com-any of ,ndia in the business of Com-uter +rainin#! +he com-any is located at :u5tsar! +he com-any is very fast #rowin# today! While conductin# my trainin# , have learnt a lot re#ardin# C?? and many more detail of which has already been #iven in this re-ort which may be read as -art of this re-ort! , have done my duty durin# trainin# with my heart & soul and can never for#et these #olden days of my study! , assure that the thin#s which , learnt in the com-any will hel- me in future career! Dence best of luc5 to Saraswati Com-uter Centre! 'C 'I'(IO*RAP,- www!c??!com www!saraswaticom-uteredu!com www!#oo#le!com www!wi5i-edia!com www!alta>vista!com www!yahoo>answers!com www!en##123!com