C++ Programming Language by Knowledge flow

58

description

C++ Programming Language by Knowledge flowC++ Programming Language by Knowledge flow.All you have to know about c++.

Transcript of C++ Programming Language by Knowledge flow

  • LEARNINGSTARTSWITHVIEWINGTHEWORLDDIFFERENTLY.

    Knowledgeflow-Amobilelearningplatformprovidesapps,eBooksandvideotutorials

    KnowledgeflowbringsyoulearningeBookofC++ProgrammingLanguage.ThiseBookisforallinformationtechnologyandcomputersciencestudentsandprofessionalsacrosstheworld.

    Followuson

    Facebook

    Googleplus

    Twitter

    Formoreinformationvisitusat

    Knowledgeflow.in

    knowledgeflowapps.blogspot.inThankyouforusingKnowledgefloweBooks

  • C++PROGRAMMINGLANGUAGE1.IntroductionofC++

    2.Generalstructure

    3.InputOutputStreams

    4.Operators

    5.VariablesandDatatypes

    6.Modifiers

    7.Controlstructures

    8.Functions

    9.Classes

    10.Objects

    11.Memberfunctions

    12.Inheritance

    13.Polymorphism

    14.MoreeBooksandApps

  • DisclaimerThiseBookcontentsisforinformationalandstudypurposesonly.TheKnowledgeflowmakesnoclaims,promises,orguaranteesabouttheaccuracy,completeness,oradequacyofthecontentsofthiseBookandnolegalliabilityorotherresponsibilityisacceptedbyKnowledgeflowforanyerrors,omissions,orstatementsonthiseBook.

  • IntroductionofC++C++isanexcellentfeaturedofprogramminglanguagethatbasedonconceptofobjectorientedprogramming,developedbyBjarneStroustrupintheearly1980satAT&TBellLabsinUSA.C++wasoriginallycalledbynameCwithclassesandrenamedC++in1983.ThenameC++comesfromtheCwithincrementoperator++thatdenotedtheenhancedversionofC.ThelanguageC++addingnewfeaturessuchclasses,objects,polymorphism,operators,memberfunctions,multipleinheritances.

    StructureofaC++program

    Includefiles

    Classdeclaration

    Memberfunctionsdefinitions

    Mainfunctionprogram

    AsimpleExampleofaC++program

    #include//includeheaderfileusingnamespacestd;intmain(){cout

  • GeneralstructureHeadercommentsIncludesheaderfileFunction{Statements}

    Example

    //MyFirstProgram#includeusingnamespacestd;intmain(){cout

  • cinstandardinputtoreadtheinputfromthekeyboard.

    return0;

    Itistheendingofthemainfunction.return0;representtheprogramtreataswithouterrorsduringexecution.ItisusuallyusetoendofC++program.

  • InputOutputstreamsInC++standardlibrariesprovideasetofinput/outputcapabilitiesoccursinstreams,whichareflowofbytes.Ifbytesflowfromadevicelikeskeyboardtomainmemory,itiscalledinputoperationandbytesflowfrommainmemorytoadevicelikeadisplayscreencalledoutputoperation.

    ThereareseveralheaderfilesinC++library.

    Itcontainsios_baseandbasic_iosclassesandtheassociatedstreambuffer.

    Itimplementsformattedinput.

    Itimplementsformattedoutput.

    Itimplementsformattedinputandoutput.

    Itcontainsbasic_fstream,basic_ifstreamandbasic_ofstreamandclasstemplateswhichimplementformattedinputandoutputonfilestreams.

    Itcontainsthebasic_stringstream,basic_istringstreamandbasic_ostringstreamandclasstemplateswhichimplementformattedinputandoutputonstring-basedstreams.

  • InputoutputfunctionsInputfunction

    Totakeinputfromuserwemusthavetousecinasinput.

    Syntax

    cin>>variable

    Outputfunction

    Totakeinputfromuserwemusthavetousecinasinput.

    Syntax

    cout

  • OperatorsOperatorsaresymbolthatinstructthecompilertoperformspecificmathematicalorlogicalmanipulations.C++hasrichsetofoperators.InC++therearefollowingtypesofoperators.

    ArithmeticOperatorsLogicalOperatorsRelationalOperatorsAssignmentOperatorsBitwiseOperators

    ArithmeticOperators

    InC++therearefollowingarithmeticoperatorssupported.

    +operator-Itaddtwooperands.

    -operator-Itsubtractssecondoperandsfromfirst.

    *operator-Itmultipliestwooperands.

    /operator-Itdividesnumeratorbyde-numerator.

    %operator-Itisamodulusoperator.

    ++operator-Itisincrementoperator,itincreasesintegervaluebyone.

    operator-Itisdecrementoperator,itdecreasesintegervaluebyone.

    LogicalOperators

    InC++therearefollowingLogicaloperatorssupported.

    ||operator-ItisLogicalORoperator,conditionbecomestruewhenanyofthetwooperandsarenon-zero.

    &&operator-ItisLogicalANDoperator,conditionbecomestruewhenboththeoperandsarenon-zero.

    !operator-ItisLogicalNOToperatorthatusetoreversethelogicalformofitsoperands.Thisoperatorwillbefalsewhenaconditionistrue.

    RelationalOperators

    InC++therearefollowingRelationaloperatorssupported.

  • ==operator-Thisoperatorcheckthevalueoftwooperandsareequalornot,ifyesthenconditionwillbetrue.

    >operator-Thisoperatorcheckthevalueofleftoperandisgreaterthanthevalueofrightone,ifyesthenconditionwillbetrue.

    =operator-Thisoperatorcheckthevalueofleftoperandisgreaterthanorequaltothevalueofrightone,ifyesthenconditionwillbetrue.

    >=,

  • VariablesVariablesarememorylocationinC++thatisusedtostoredataonmemory.Variablenamecanconsistofalphabets,numbersandstartwithunderscorecharacterandthefirstcharacterofvariablesshouldalwaysbealphabetnotdigitandblankspacenotallowed.

  • DataTypesAdatatypesworkaswhichtypesofdatawillstoreinvariablesandalsoworkasmemorystorageofdata.Datatypeseitheruserdefineddatatypesorstandarddatatypes.

    TherearefourmaindatatypesinC++.

    1. char2. int3. float4. double

    char

    Thisdatatypeisusedforcharacterdatatypestorepresentslettersandsymbols.

    Signechar-representsignedcharacter.unsignedchar-representunsignedcharacter.char-representcharacter.wcahr_t-representwidecharacter.char16_t-representUTF-16character.char32_t-representUTF-32character.

    int

    Thisdatatypeisvalueswhichhavenodecimalanditcanbepositiveandnegativesuchas-10or-10.Itsvaluesrangingfrom-32768to32767.Itdoesnothavefractionpart.

    int.shortint.lontint

    float

    Thisdatatypecontainafloatingpointnumberandanumberthatcontainafractionpart.Itsvaluesrangingisbetween+/-3.4e38to+/-3.4e38.Itusuallyfloatingpointnumbershasdecimalplaces.

    double

    Thisdatatypeislargerealnumberanditsvaluesrangingisfrom1.7x10-308to1.7x10+308.

  • ModifiersIfwewanttochangethenatureandworkingrulesofanydatatypes,thensomespecificwordsareusedthesearecalledmodifiers.

    TherearetwotypesofmodifiersusedinC++.

    SizemodifiersSignmodifiers

    SizeModifiers

    Ifuserwantstoincreaseordecreasetheactualsizeofdatatypesthenwemusthavetousesizemodifiers.TherearetwotypesofSizemodifierssupportedinC++program.

    Longtoincreasethesize.Shorttodecreasethesize.

    SignModifiers

    Ifwewanttofixthesignofthedatatypesthenwecanusesignedandunsignedmodifiers.Bytheuseofsignwecanfixthedatatypestostoreonly+Positivevalueandwithuseofunsignedwecanfix-Positivevaluesonly.

  • ControlstructuresControlstructuresarestatementsthatmodifythesequenceofprogramincertainconditions,duringtheexecutionitmayrepeatthecodeortakedecisions.

    InC++controlstructuresinstructtospecifythatwhatdonebyourprogram.

    TherearethreecategoriesofControlstructures.

    SelectionStatementsIterationStatementsJumpStatements

    SelectionStatements

    TherearesomeselectionstatementssupportedinC++program.

    ifStatementifelsestatementSwitchstatement

    IterationStatements

    TherearesomeIterationstatementssupportedinC++program.

    forloopwhileloopdowhileloop

    JumpStatements

    TherearesomeJumpstatementssupportedinC++program.

    gotobreakcontinue

  • ifStatementSyntax

    if(expression){Statements}

    Program

    #includeusingnamespacestd;voidmain(){inta=400;intb=800;if(b>a){cout

  • ifelseStatementSyntax

    if(expression){Statements}else{Statements}

    Program

    #includeusingnamespacestd;voidmain(){inta=100;intb=200;if(a>b){cout

  • switchStatementSyntax

    switch(expression){case1:Statementsbreakcase2:Statementsbreak..defaultStatements}

    Program

    #includeusingnamespacestd;intmain(void){intday;cout>day;switch(day){case1:cout

  • break;case4:cout
  • forloopStatementSyntax

    for(initialization;condition;increment)

    Program

    #includeusingnamespacestd;intmain(void){inti;for(i=1;i

  • whileloopStatementSyntax

    while(condition)statement;

    Program

    #includevoidmain(){intn;cout0:;cin>>n;while(n>0){cout

  • dowhileStatementSyntax

    do{statement;}while(condition);

    Program

    #includeusingnamespacestd;intmain(){intn;cout>n;do{cout

  • breakStatementSyntax

    break;

    Program

    #includeintmain(){inti;for(i=0;i

  • gotoStatementSyntax

    gotolabel;..label:

    Program

    #includevoidmain(){inti;cout>i;switch(i){case1:cout

  • ExitedLoop

  • continueStatementSyntax

    continue;

    Program

    #includeusingnamespacestd;intmain(){inta=9;do{if(a==13){a=a+1;continue;}cout

  • FunctionsFunctionsareseparateindividualmodulesdesignedinC++programs.

    Afunctionisanareawherewecandeclarethecalculationpartandcancallituptomultipletimesbutappearsinthecodeonce.

    Bymakingfunctionswecandecomposeourprograminseparateblockswhichareinter-linkedwithmain.

    Syntax

    main(){functionbodyreturn0;}

    TherearetwotypesoffunctionsinC++.

    Libraryfunction.Userdefinesfunction.

    Pre-definedorLibraryfunction

    Thosefunctionswhicharepredefineintheirheaderfilesi.e.(math.h,time.h,ctype.h)andcandirectlyusewithoutgivingthedefinitionofthefunction.

    Thesefunctionsareinvokedthroughtheirspecificheaderfile.

    Functionusing

    ceil(),floor()

    Example

    #include#includevoidmain(){doublen;cout>n;//Computethesmallestandthelargestoftherealnumbercout

  • cout
  • ClassesAclassisatechniquetoholdthedatastructuresandfunctions.Itisawaytoallowusertocreatingandseparatespecificuserdefineddatatypes.

    ItisthemostpowerfulfeatureofC++.

    Whenwedefinedtheclassstartswithakeywordclassfollowedbyaclassnameandthebodyoftheclassenclosedwithtwocurlybracesandusesemicolonattheendofclasstoterminateitsameasstructure.

    Thekeywordsprivateandpublicarecalledvisibilitylabels.

    Wordprivatemakesthedataandfunctionprivateandaccessibleinsideonlytheclasswhereas,keywordpublicmakesthedataandfunctionpublicandcanbeaccessedbothoutsideandinsidetheclass.

    Declarationofclass

    Classclass_name{private:somedata;functiondeclarations;public:somedata;functiondeclarations;};

    Example

    classimage{private:intwidth;intheight;char*pixels;public:intget_width();intget_height();charget_pixel(intx,inty);voidset_pixel(intx,inty,charvalue);

  • voidsave(char*filename);};

  • ObjectsInclassinstantiationofdatatypesknowsasobjectsinC++.

    Relationshipofobjectwithclasssameasvariablehaswithdatatypes,classvariablesarealsoknownasobjectsinC++.

    Anobjectcontainsthepropertyofaclass.

    Example

    Productx;

    Here,xistheobjectoftypeproduct.Oneormorethanoneobjectscanbedeclaredinonestatement.

    Example

    Productx,y,z;

    Syntax

    Class_nameObject_name{Public}

    Example

    classY{//membersofclassY};intmain(){Yobj;//declareaclassobjectofclasstypeY}

  • MemberfunctionsinClassesInC++memberfunctionsarethosefunctionswhicharedeclareinsideandoutsidethedefinitionoftheclass.Itcanbedefinedintotwoplaces.

    Insidetheclassdefinition.Outsidetheclassdefinition.

    Insidetheclassdefinition

    Inthisdefinitionwecandirectlydefinethefunctioninsidetheclassdefinition.

    Example

    classProduct{intproductID;floatprice;public:voidgetdata(inta,floatb);//functionvoidputdata(void)//definedinsideclassdefinition{Cout

  • public:intside;intgetVolume();}//functionintcube::getVolume()//definedoutsideclassdefinition{returnside*side*side;}

  • InheritanceInheritanceisoneofthemostimportantfeaturesofObjectOrientedProgramming.

    Itisatechniquetoreusetheexistingclasseswithoutanymodificationandproducehierarchicalrelationshipbetweenthem.

    Itacquiresthepropertiesandcharacteristicsofoneclasstoanotherclass.

    AclasswhichinheritedthepropertiestoanotherclassknownasParent,BaseclasswhereasclasswhichinheritsthepropertiesofanotherclassknownasDerived,suborchildclass.

    TherearefivetypesofInheritanceinC++.

    1. SingleInheritance.

    2. MultipleInheritances.

    3. MultilevelInheritance.

    4. HierarchicalInheritance.

    5. HybridInheritance.

    Syntax

    class_namesubclass_name:accessed_modebase_class_name{MembersofSubclass};

    Example

    #includeusingnamespacestd;//ParentclassclassCars{public:intWheels=4;};//Derivedclass

  • classBike:publicCars{public:inttyres=2;};intmain(){Bikeb;Cout
  • MultilevelInheritance

    Inthisinheritanceaclassderivedfromanotherderivedclassinheritsfromoneparentclass.

    HierarchicalInheritance

    Inthisinheritancemultiplederivedclassesinheritfromoneparentclass.

    HybridInheritance

    Itisthecombinationofbothmultilevelandmultipleinheritance.

  • PolymorphismPolymorphismisoneofstrategicfeaturesofobjectorientedprogrammingthatsmeanhavingmanyforms.Polymorphismrollsupwhenahierarchyofclassesandtheyarerelatedbyinheritance.

    TherearetwotypesofpolymorphisminC++programming.

    Compiletimepolymorphism.Runtimepolymorphism.

    Compiletimepolymorphism

    Inthispolymorphismobjectisenclosingtothefunctioncallatthecompiletimeitselfknownasstaticbindingorstaticlinkageorearlybinding.

    Runtimepolymorphism

    Inthispolymorphismobjectisenclosingtothefunctioncallattheruntime.

    Exampleofpolymorphism

    #includeusingnamespacestd;classShapes{protected:intwidth,height;public:Shapes(intx=0,inty=0){width=x;height=y;}intarea(){cout

  • public:Rectangle(inta=0,intb=0){Shapes(a,b);}intarea(){cout
  • shapes=&tria;//calltrianglearea.shapes->area();return0;}

    Aftercompilingandexecutedtheabovecodethefollowingresultwillbereceived.

    Parentclassarea

  • Knowledgeflow:moreeBooksandAppsGetmoreeBooksGetmoreappsfromGooglePlaystoreGetmoreappsfromAmazonappstore