还剩24页未读,继续阅读
本资源只提供10页预览,全部文档请下载后查看!喜欢就下载吧,查找使用更方便
文本内容:
C/C++Programming interviewquestions andanswersBySatish Shetty,July14th,What isencapsulationContaining andhiding information about an object,such as internal datastructures andcode.(使蔺离)Encapsulation isolatesB theinternal complexityof an objects operationfrom therest of the(收益)application.For example,a clientcomponent askingfor netrevenue from a businessobject neednot know thedatas origin.What is inheritanceInheritance allowsone class to reuse the stateand behaviorof anotherclass.The derived class inheritstheproperties andmethod implementationsof the base class and extendsit byoverriding methodsandadding additionalproperties andmethods.What isPolymorphismPolymorphism allows a clientto treatdifferent objects in the same wayeven ifthey werecreated from(展现)different classesand exhibitdifferent behaviors.(实现)You can use implementation inheritance to achieve polymorphism in languagessuch asC++and Java.What isreference referenceis a name that acts as an alias,or alternativename,for apreviously definedvariable or anobject.prepending variablewith symbolmakes itas reference.for example:int a;int b=a;读ampWhat ispassing by referenceMethod ofpassing argumentsto a function whichtakes parameterof typereference.for example:void swapintx,inty inttemp=x;二x y;y=temp;int a=2,b=3;swap a,b;Basically,inside the function therewont beany copyof thearguments xand Hyninstead theyrefer tooriginalvariables aand b.so noextra memoryneeded topass argumentsand it is moreefficient.When douse const reference argumentsin function不经意欧a Usingconst protectsyou againstprogramming errorsthat inadvertentlyI alterdata.b Usingconst allowsfunction toprocess bothconst andnon-const actual arguments,while a functionwithout constin theprototype canonly acceptnon constantarguments.c Usinga constreference allowsthe functionto generate and use a temporary variable appropriately.When aretemporary variablescreated byC++compilerProvided that function parameter is aconstreference1,compiler generatestemporaryvariableinfollowing2ways.a Theactual argument is the correct type,but it isnt LvaluedoubleCubeconst doublenum二num num*num*num;return num;double temp=
2.0;double value=cube
3.0+temp;//argumentis a expressionand not a Lvalue;b Theactualargumentis of the wrongtype,but of a typethat can be convertedto thecorrect typelongtemp=3L;double value=cuberoot temp;//long todouble conversionWhat is virtualfunctionWhen derived class overridesthe base class methodby redefiningthe samefunction,then ifclient wantsto access redefinedthe methodfrom derivedclass througha pointerfrom base class object,then youmustdefine thisfunction inbase class as virtualfunction.class parentvoid Showcout«Him parent«endl;;class child:public parentvoidShow{cout«nim child«endl;;parent*parent_object_ptr=new child;parent_object_ptr-show//calls parent-show inow wegoto virtualworld...class parentvirtualvoidShowcout«Him parent«endl;;class child:public parentvoidShowcout«nim child1*«endl;;parent*parent_object_ptr=new child;parent_object_ptr-show//calls child-showWhat ispure virtualfunction orwhat is abstract classWhen you defineonly functionprototype in a base class withoutimplementation anddo thecomplete实现implementationin derivedclass.This base class is called abstract class andclient wontable toinstantiatean objectusing thisbaseclass.You canmake apure virtualfunction orabstractclassthis way..class Boovoid foo=0;Boo MyBoo;//compilation errorWhat is Memoryalignment趋向The termalignment primarilymeans thetendency of an addresspointer valueto bea multipleofsome powerof two.So a pointer with two bytealignment has a zeroin theleast significantbit.And a pointer withfour bytealignment hasa zeroin boththe twoleast significantbits.And soon.More alignmentmeans alonger sequenceof zerobits in the lowestbits of a pointer.What problemdoes the namespace featuresolveMultiple providersof librariesmight usecommon globalidentifiers causing a namecollision when anapplication triesto linkwithtwoor moresuch libraries.The namespacefeature surroundsa librarys消除external declarationswith aunique namespacethat eliminatesthe potentialfor thosecollisions.namespace[identifier]{namespace-body}A namespace declaration identifiesand assignsa nametoadeclarative region.The identifierin anamespacedeclarationmust beunique in the declarativeregion inwhich itis used.Theidentifier is thenameof thenamespace andis used to referenceits members.What isthe useof usingdeclaration范围A usingdeclaration makesit possibleto useanamefromanamespace withoutthe scopeoperator.迭代器What is an Iterator class穿过A class that is usedtotraverse throughthe objectsmaintained by a container class.There arefivecategories ofiterators:input iterators,output iterators,forward iterators,bidirectional iterators,randomaccess.An iteratoris anentity thatgives accessto the contents of a containerobject withoutviolatingencapsulation constraints.Access to the contentsis grantedonaone-at-a-time basisin order.The ordercan be storageorder asin listsand queuesor somearbitrary orderasinarray indicesor accordingtosome orderingrelation asin anordered binarytree.The iteratoris aconstruct,which providesaninterface that,when called,yields eitherthe nextelement in the container,or somevalue denotingthe factthat there areno moreelements toexamine.Iterators hide the detailsof accessto andupdate of theelements of a container class.Something likeapointer.悬挂What isa danglingpointerA danglingpointer ariseswhen youusethe address ofan objectafter itslifetime isover.This mayoccurin situationslike returningaddresses of the automaticvariables froma functionor usingthe addressofthe memoryblock afteritisfreed.What doyou meanby StackunwindingIt isa processduring exceptionhandling when the destructoris called for alllocal objectsin the stackbetween theplace where the exceptionwas thrownand where itiscaught.抛出异常与栈展开stack unwinding抛出异常时,将暂停目前函数的执行,开始查找匹配的子句首先检查自身与否在catch throw块内部,假如是,检查与该有关的子句,看与否可以处理该异常假如不能处理,try trycatch就退出目前函数,并且释放目前函数的内存并销毁局部对象,继续到上层的调用函数中查找,I直到找到一种可以处理该异常的这个过程称为栈展开当处理该异常的I catchstack unwindingo结束之后,紧接着该之后的点继续执行catch catchI为局部对象调用析构函数
1.如上所述,在栈展开的过程中,会释放局部对象所占用的内存并运行类类型局部对象的析构函数但需要注意日勺是,假如一种块通过动态分派内存,并且在释放该资源之前发生异常,new该块因异常而退出,那么在栈展开期间不会释放该资源,编译器不会删除该指针,这样就会导致内存泄露析构函数应该从不抛出异常
2.在为某个异常进行栈展开的时候,析构函数假如又抛出自己的未经处理的另一种异常,将会导致调用原则库函数一般函数将调用函数,导致程序欧非正常退出terminate terminateabort J因此析构函数应该从不抛出异常异常与构造函数
3.假如在构造函数对象时发生异常,此时该对象可能只是被部分构造,要保证可以合适的撤销这些已构造的组员未捕捉时异常将会终止程序
4.不能不处理异常假如找不到匹配日勺程序就会调用库函数catch,terminateName theoperators thatcannot beoverloadedsizeof,:What isa containerclass What are thetypes ofcontainer classesA containerclass isa class that isusedto holdobjectsinmemory orexternal storage.A containerclassacts asa genericholder.Acontainerclass hasa predefinedbehavior and a well-known interface.Acontainer class isasupporting classwhose purposeis tohidethetopology used for maintainingthe listofobjects inmemory.When acontainerclasscontains agroup ofmixed objects,the container is calleda不均匀的多样勺heterogeneous IH container;when the containerisholding agroup ofobjects thatare单一的均匀日勺all the same,thecontaineris calleda homogeneouscontainer.标准容器类特点顺序性容器vector从后面快速的插入与删除,直接访问任何元素从前面或后面快速的插入与删除,直接访问任何元素dequelist双链表,从任何地方快速插入与删除关联容器set快速查找,不允许重复值multiset快速查找,允许重复值一对多映射,基于关键字快速杳找,不允许重复值mapmultimap一对多映射,基于关键字快速查找,允许重复值容器适配器stack后进先出先进先出queue最高优先级元素总是第一个出列priority_queueWhat isinline function替代The_inline keywordtells the compiler tosubstitute thecode within the functiondefinition Base调用class objectspointer caninvoke methodsinderivedclass objects.You canalso achievepolymorphismin C++by functionoverloading andoperator overloading.What isconstructor orctor变量歹表?Constructor createsan object and initializesit.It alsocreates vtableU forvirtual functions.It isdifferent fromother methodsina class.What isdestructorDestructor usuallydeletes anyextra resourcesallocated by the object.What isdefault constructorConstructorwith noarguments orall thearguments hasdefault values.What iscopy constructorConstructorwhich initializesthe itsobject membervariablesby shallowcopying with another objectof the same class.If youdont implementone inyour classthen compiler implements onefor you.for example:Boo Obj110;//calling BooconstructorBoo0bj20bjl;//calling boocopy constructorfor everyinstance ofa function call.However,灵舌性.substitution occursonly atthe compilersdiscretion7For example,the compilerdoes notinlineafunctionif itsaddress istaken orif itis toolarge toinline.使用预处理器实现,没有了参数压栈,代码生成等一系列的操作,因此,效率很高,这是它J在中被使用的一种重要原因CWhat isoverloadingWith the C++language,you canoverload functionsand operators.Overloading isthe practiceofsupplying more than onedefinition fora givenfunction namein the same scope.-Any twofunctions ina setof overloadedfunctions musthave differentargument lists.-Overloading functionswith argumentlists of the sametypes,based onreturn typealone,is anerror.What isOverridingTo overridea method,a subclass of the classthatoriginally declaredthe methodmust declarea methodwith the same name,return typeorasubclassofthat return type,and sameparameter list.Thedefinition ofthe methodoverriding is:•Must havesame method name.•Must havesame data type.•Must havesame argumentlist.Overriding a method meansthat replacinga methodfunctionality inchild class.To implyoverridingfunctionality weneed parentand child classes.In thechildclassyou definethesamemethod signatureasone definedin theparent class.What isthis pointerThethis pointerisapointer accessible only within the member functions ofa class,struct,or uniontype.It pointsto the object forwhich themember function iscalled.Static member functions donot have a thispointer.When a non-static member functioniscalledforanobject,theaddressofthe object is passed asa hiddenargument to thefunction.For example,the followingfunctioncallmyDate.setMonth3;解释can beinterpreted thisway:setMonth myDate,3;The objectsaddress isavailable fromwithinthememberfunctionas the this pointer.It islegal,thoughunnecessary,to usethethis pointer whenreferring tomembers ofthe class.What happenswhen youmake callHdelete this;陷阱/误区.The codehas twobuilt-in pitfallsFirst,if itexecutes ina memberfunction foran extern,static,or automaticobject,the programwill probablycrash assoon asthe deletestatement executes.There is no portableway foranobjectto tellthat itwas instantiatedon the heap,so the class cannotassertthat itsobject isproperly instantiated.Second,whenanobject commitssuicide thisway,the using死亡/转让.program mightnotknowabout itsdemise Asfar asthe instantiatingprogram isconcerned有关町the objectremains inscope andcontinues toexist even though theobject diditself in.Subsequent后来的间接弓用(重弓用指针,dereferencing Idereferencin pointerI dereferencinaoperator取值运算符)不幸.ofthepointer canand usuallydoes lead to disasterYoushould neverdo this.Since compilerdoes notknow whethertheobjectwas allocatedon thestack oronthe heap,delete thiscould causea disaster.执行How virtual functions are implemented C++Virtual functionsareimplementedusingatable offunction pointers,called the vtable.There isone entryinthe tableper virtualfunction inthe class.This tableis createdby theconstructor ofthe class.When aderivedclass isconstructed,its baseclass isconstructed firstwhich createsthevtable.If thederived classoverridesany ofthebaseclasses virtualfunctions,those entriesinthevtable areoverwritten by thederived classconstructor.This iswhy youshould nevercall virtualfunctions froma constructor:becausethe vtableentries for theobjectmay nothave beenset upby thederivedclassconstructor yet,so youmightend upcalling baseclass implementationsof thosevirtual functionsWhat is namemangling in C++The process of encodingthe parametertypes withthefunction/methodnameinto aunique name is callednamemangling.The inverseprocess iscalled demangling.For exampleFoo::barint,long constis mangledas bar_C3Fooir.、For a constructor,the methodnameisleft out.That isFoo::Fooint,long constis mangledas C3FooiF.What isthe difference between apointer anda referenceAreference must always refer to someobject and,therefore,mustalwaysbe initialized;pointers donothave suchrestrictions.A pointercan bereassigned topoint todifferent objectswhile areference alwaysrefersto anobject withwhich itwas initialized.How areprefix andpostfix versionsof operator++differentiatedThe postfixversion ofoperator++hasadummy parameterof typeint.The prefixversion doesnot havedummyparameter.What isthe differencebetween constchar^myPointer andchar^const myPointerConstchar*myPointer isa non constant pointer to constantdata;while char*const myPointeris aconstantpointer tononconstantdata.How canI handleaconstructorthat failsthrow an exception.Constructors donthave areturntype,so itsnot possibleto usereturn codes.The bestwayto signalconstructor failureis thereforeto throwan exception.How canI handlea destructorthat failsWritea messagetoalog-file.But donot throwan exception.The C++rule is that youmust neverthrowanexception froma destructorthat isbeing calledduring the*stack unwinding1processof another exception.For example,if someonesays throwFoo,the stackwillbe unwoundso all thestackframes betweenthe throwFoo andthe}catch Fooe{will getpopped.This iscalled stackunwinding.During stackunwinding,all thelocal objectsin allthose stackframes aredestructed.If oneof thosedestructorsthrows anexception sayit throwsa Barobject,theC++runtime systemisinano-winsituation:should itignore theBar andend up inthe}catch Fooe{whereitwas originallyheadedShould itignore theFoo andlook fora}catch Bare{handler Thereisnogood answer—eitherchoice losesinformation.So theC++language guaranteesthat itwill callterminate atthispoint,and terminatekills theprocess.Bang youredead.What isVirtual DestructorUsingvirtual destructors,you candestroy objectswithout knowingtheir type-thecorrectdestructor fortheobject isinvoked usingthe virtualfunction mechanism.Note thatdestructors canalso bedeclared aspurevirtualfunctionsfor abstractclasses.if someone will derivefrom your class,and ifsomeone willsay newDerived”,where Derived”isderived fromyourclass,and ifsomeonewillsay deletep,wheretheactual objects type isDerived butthepointer p*stypeis yourclass.Can youthink ofa situationwhere yourprogram wouldcrash withoutreaching thebreakpointwhich youset atthe beginningof mainQC++allows fordynamic initializationof globalvariables beforemain isinvoked.It ispossible thatinitializationof globalwill invokesome function.If thisfunction crashesthe crashwill occurbeforemain isentered.Name twocases whereyou MUSTuse initialization list asopposed to assignment inconstructors.Both non-static const data membersand referencedata memberscannot beassigned values;instead,youshould useinitializationlistto initialize them.Can youoverload afunction basedonly onwhether aparameterisa valueor areferenceNo.Passing by value andbyreferencelooks identicalto thecaller.What arethe differencesbetween aC++struct andC++class标识符The defaultmember andbaseclassaccess specifiersare different.The C++struct hasall thefeatures ofthe class.The onlydifferences arethatastruct defaultsto publicmemberaccess andpublic baseclass inheritance,anda class defaultsto theprivate accessspecifier andprivatebaseclassinheritance.What doesextern nCnint funcintFoo accomplish实现/到达/完成?It willturn offHname mangling*for funcso thatone canlink tocode compiledby aC compiler.How doyou accessthe staticmember ofa classClassName::StaticMemberNameWhat ismultiple inheritancevirtualinheritance What are itsadvantages anddisadvantages通过Multiple Inheritanceistheprocess wherebya childcan bederived frommorethan one parentclass.功能The advantageof multiple inheritance isthat itallowsaclasstoinherit thefunctionality ofmore建模thanonebaseclassthus Blitallowing formodeling ofcomplex relationships.The disadvantageof昆舌multipleinheritanceisthat it canleadtoa lotof confusion7L ambiguitywhen twobase classesimplementamethodwiththesamename.What arethe access privileges inC++What isthe defaultaccess levelTheaccessprivilegesinC++are private,public andprotected.The defaultaccess levelassigned tomembersofaclass is private.Private membersofaclass are accessibleonlywithintheclassandbyfriends oftheclass.Protected membersareaccessiblebytheclass itselfand itssub-classes.Publicmembers ofaclass can beaccessed byanyone.嵌套What isa nestedHtl class Why can it beuseful被附上的A nestedclassisaclassenclosed withinthe scopeofanotherclass.For example://Example1:Nested class//class OuterClass{class NestedClassII...;II...;Nested classesare usefulfor organizingcode andcontrolling accessand dependencies.Nested classesobeyaccess rulesjust likeother partsofaclass do;so,in Example1,if NestedClassis publicthen any实现code canname itas OuterClass::NestedClass.Often nestedclasses containprivate implementation因此/因此details,and aretherefore madeprivate;in Example1,if NestedClassisprivate,then onlyOuterClass!s membersand friendscanuseNestedClass.实彳列化Whenyouinstantiate asouter class,it wontinstantiate insideclass.Whatisa localclassWhycanitbe usefullocalclassisaclassdefined withinthe scopeofafunction—any function,whether amemberfunctionora freefunction.For example://Example2:Local class//int fclassLocalClass〃…;〃…Like nestedclasses,local classescan bea usefultool formanaging codedependencies.Can a copy constructoraccept anobject ofthesameclassasparameter,insteadof referenceoftheobjectNo.It isspecified inthe definitionofthecopy constructoritself.It shouldgenerateanerror ifaprogrammer specifiesacopyconstructor witha firstargument thatis anobjectandnotareference,couseinfinite recursive!右花括号close brace;close curly;RIGHT CURLYBRACKET;EBRACE左花括号open brace;open curly;OBRACE左中括号小括号left squarebracket;left bracket;bracketleft,opening;vierkante haaklinksParentheses[pargnOasiz]bracket尖括号angle brackets冒号colon箭头Arrow symbol〃Boo Obj2=Objl;calling boocopy constructorWhenare copyconstructors calledCopyconstructors arecalled infollowing cases:a whenafunctionreturns anobject ofthat classby valuebwhentheobject ofthat classispassedbyvalueasanargumenttoa functioncwhen youconstruct anobject basedon anotherobject ofthesameclassd Whencompiler generatesa temporaryobjectWhat isassignment operatorDefaultassignment operatorhandles assigningone objectto anotherofthesameclass.Member tomembercopy shallowcopyWhat are alltheimplicit memberfunctions oftheclassOr whatareallthe functionswhichcompilerimplementsfor usif wedont defineone.default ctorcopyctorassignment operatordefaultdestructor addressoperatorWhat is conversion constructorconstructorwithasingle argumentmakes thatconstructor asconversion ctorand itcanbeusedfortypeconversion.for example:class Boopublic:Boo inti;);Boo BooObject=10;//assigning int10Boo objectWhatisconversionoperatorclass canhave apublic methodfor specificdata typeconversions.for example:class Boodoublevalue;public:Booint ioperatordoublereturn value;);Boo BooObject;double i=BooObject;//assigning objectto variablei oftype double,now conversionoperator getscalledtoassignthe value.Whatisdiff betweenmalloc/free andnew/deletemalloc allocatesmemory forobject inheap butdoesnt invokeobjects constructor to initiallizetheobject.new allocatesmemory andalso invokesconstructortoinitializetheobject.malloc andfree donot supportobject semanticsDoesnot constructand destructobjectsstring*ptr=string*malloc sizeofstringAre not safeDoesnot calculatethe sizeofthe objects thatit constructReturnsapointerto voidint*p=int*mallocsizeofint;int*p=new int;Arenotextensible newand deletecanbeoverloaded ina classdeletefirst callstheobjectstermination routinei.e.its destructorand thenreleases thespace theobjectoccupied ontheheapmemory.If anarray ofobjects wascreated usingnew,then deletemust betoldthatitis dealingwith anarray bypreceding thename withan empty[]:-Int_t*my_ints=new Int_t
[10];what isthe diffbetween newand Hoperator new”?“operatornew1works likemalloc.Whatisdifferencebetweentemplate andmacroThere isno wayforthecompiler toverify that the macroparameters areof compatibletypes.The macroisexpanded withoutany specialtype checking.If macroparameter hasa post-incremented variablelike c++,the incrementis performedtwo times.Because macrosare expandedbythepreprocessor,compiler errormessages willrefertothe expandedmacro,rather thanthe macrodefinition itself.Also,the macrowill showupinexpanded formduringdebugging.for example:Macro:#define mini,j iji:jtemplate:templateclass TTminT i,Tj returniji:j;WhatareC++storage classesautoregisterstatic externauto:the default.Variables areautomatically createdand initializedwhen theyare definedandare destroyedattheend ofthe blockcontaining theirdefinition.They arenot visibleoutside thatblockregister:atypeof autovariable,a suggestiontothecompiler touseaCPU registerforperformancestatic:a variablethatisknown onlyinthefunction that contains itsdefinition butis neverdestroyed andretains=keep itsvalue betweencalls tothatfunction.It existsfrom the time theprogram beginsexecutionextern:a staticvariable whosedefinition andplacement isdetermined whenall objectand librarymodulesare combinedlinked toform theexecutable codefile.It canbe visibleoutside thefile whereitis defined.Whatarestorage qualifiersinC++They are..constvolatilemutableConstkeyword indicates that memoryonce initialized,should notbe alteredbyaprogram.volatilekeyword indicatesthatthevalue inthe memorylocation canbe alteredeventhoughnothing intheprogramcode modifiesthecontents.for exampleif youhaveapointertohardware locationthatcontainsthetime,where hardwarechanges thevalue ofthis pointervariable andnot theprogram.The intentof thiskeywordto improvethe optimizationability ofthecompiler.mutable keywordindicatesthatparticular memberofastructure orclasscanbe alteredeven ifaparticular structurevariable,class,orclassmemberfunctionis constant.struct datacharname
[80];mutable doublesalary;constdataMyStruct={Satish Shettyn,1000};//initlized bycompilerstrcpyMyStruct.name,nShilpa Shetty1;//compiler errorMyStruct.salaray=;//compiler ishappy allowed。
个人认证
优秀文档
获得点赞 0