C++InterviewQuestion.docx
- 文档编号:6131531
- 上传时间:2023-01-04
- 格式:DOCX
- 页数:12
- 大小:44.64KB
C++InterviewQuestion.docx
《C++InterviewQuestion.docx》由会员分享,可在线阅读,更多相关《C++InterviewQuestion.docx(12页珍藏版)》请在冰豆网上搜索。
C++InterviewQuestion
C++InterviewQuestions
Name:
ZhuoDu
1.Howdoyoudecidewhichintegertypetouse?
Itdependsonourrequirement.Whenwearerequiredanintegertobestoredin1byte(meanslessthanorequalto255)weuseshortint,for2bytesweuseint,for8bytesweuselongint.Acharisfor1-byteintegers,ashortisfor2-byteintegers,anintisgenerallya2-byteor4-byteinteger(thoughnotnecessarily),alongisa4-byteinteger,andalonglongisa8-byteinteger.
2.Whatdoesexternmeaninafunctiondeclaration?
Anexternfunctionoramembercanbeaccessedoutsidethescopeofthe.cppfileinwhichitwasdefined.
3.What’stheautokeywordgoodfor?
Itdeclaresanobjectwithautomaticstorageduration.Whichmeanstheobjectwillbedestroyedattheendoftheobjectsscope.Allvariablesinfunctionsthatarenotdeclaredasstaticandnotdynamicallyallocatedhaveautomaticstoragedurationbydefault.
4.Definealinkedlistnodewhichcontainsapointertoitself.
#include
intmain(){
void*ptr;
ptr=&ptr;
return0;
}
5.HowdoIdeclareanarrayofNpointerstofunctionsreturningpointerstofunctionsreturningpointerstocharacters?
Ifyouwantthecodetobeevenslightlyreadable,youwillusetypedefs.
typedefchar*(*functiontype_one)(void);
typedeffunctiontype_one(*functiontype_two)(void);
functiontype_twomyarray[N];//assumingNisaconstintegral
char*(*(*a[N])())();
6.HowcanIdeclareafunctionthatreturnsapointertoafunctionofitsowntype?
some_typef()
{
staticintcnt=1;
std:
:
cout< : endl; } intmain() { f()()()...();//ncalls } 7.WhatcanIsafelyassumeabouttheinitialvaluesofvariableswhicharenotexplicitlyinitialized? Itdependsoncomplierwhichmayassignanygarbagevaluetoavariableifitisnotinitialized. 8.HowcanIcreateatwo-dimensionaldynamicarray? Adynamic2Darrayisbasicallyanarrayof pointerstoarrays.Weshouldinitializeitusingaloop,likethis: int**ary=newint*[rowCount]; for(inti=0;i ary[i]=newint[colCount]; 9.HowcanIdeallocateatwo-dimensionaldynamicarray? Codetodeallocatethedynamicallyallocated2Darrayusingdeleteoperatorisasfollows, voiddestroyTwoDimenArrayOnHeapUsingDelete(int**ptr,introw,intcol) { for(inti=0;i delete[]ptr[i]; } delete[]ptr; } 10.Whatisavirtualfunction? A virtualfunction isamember function thatyouexpecttoberedefinedinderivedclasses.Whenyourefertoaderivedclassobjectusingapointerorareferencetothebaseclass,youcancalla virtualfunctionforthatobjectandexecutethederivedclass'sversionofthe function. 11.HowdoIdodynamicbinding? DynamicBinding: thedecisionismadeatrun-timebaseduponthetypeoftheactualobject.CheckedVector: : operator[]willbecalledinthiscaseas(*vp->vptr[1])(vp,0). Usewhenthederivedclassesmaybeabletoprovideadifferent(e.g.,morefunctional,moreefficient)implementationthatshouldbeselectedatrun-timeUsedtobuilddynamictypehierarchies&toform“abstractdatatypes”C 12.WhenshouldIusealocalstaticvariableinafunction? a staticvariable isa variable thathasbeen allocatedstatically—whose lifetime or"extent"extendsacrosstheentirerunoftheprogram. 13.WhenshouldIuse“register”todeclareavariable? Usingregisterkeyword,youareinstructingthecompilertosavethecurrentdataintheregistermemoryoftheprocessor.Dataintheregistercanbefetchedquicklybytheprocessorbecauseofthelocalityofdata.Thedataiswiththeprocessor.Fetchingdatafromsecondarymemory(e.g.Harddisk)ormainmemory(RAM)requiresinstructioncycles. Butregistermemoryislimited! ! ItsnegligibleifyouwillcompareitwiththeamountyoucanhaveonRAMorHardDisks. 14.CanIputafunctionintoastruct? Yes,a struct isidenticaltoa class exceptforthedefaultaccesslevel(member-wiseandinheritance-wise).(andtheextrameaning class carrieswhenusedwithatemplate) 15.HowdoIinitializeapointertoafunction? classFoo{ private: staticdouble(*my_ptr_fun)(double,double); }; doublebar(double,double); double(*Foo: : my_ptr_fun)(double,double)=&bar; Whateveryouwouldneedastaticfunctionpointerforanyway. Thisiscalled initialization. instantiation meanssomethingdifferentinC++. 16.Arearraysrow-majororcolumn-major? row-major 17.Whatisthedifferencebetweenanormalpointerandavoidpointer? Genericpointeroftype 'void*' iscompatiblewithany(data-)pointer,butyoucannotusethefollowingoperatorsonit: +-++--+=-=*->[] 18.Whatwillthefollowingprogramdo? voidmain() { inti; chara[]="String"; char*p="NewSring"; char*Temp; Temp=a; a=malloc(strlen(p)+1); strcpy(a,p);//Linenumber: 9// p=malloc(strlen(Temp)+1); strcpy(p,Temp); printf("(%s,%s)",a,p); free(p); free(a); }//Linenumber15// a)Swapcontentsofp&aandprint: (Newstring,string) b)Generatecompilationerrorinlinenumber8 c)Generatecompilationerrorinlinenumber5 d)Generatecompilationerrorinlinenumber7 e)Generatecompilationerrorinlinenumber1 b) 19.enumnumber{a=-1,b=4,c,d,e}; Whatisthevalueofe? (a)7 (b)4 (c)5 (d)15 (e)3 (d)15 20.Whatisthedifferencebetweenoverloadingandoverriding? Themostbasic difference isthat overloading isbeingdoneinthesameclasswhilefor overriding baseandchildclassesarerequired.Overriding isallaboutgivingaspecificimplementationtotheinheritedmethodofparentclass. 21.Whatisthedifferencebetweenprivateandprotectedaccess? Privatevariables,arevariablesthatarevisibleonlytotheclasstowhichtheybelong. Protectedvariables,arevariablesthatarevisibleonlytotheclasstowhichtheybelong,andanysubclasses. 22.Whenarecopyconstructorscalled? 1.Whenanobjectoftheclassisreturnedbyvalue. 2.Whenanobjectoftheclassispassed(toafunction)byvalueasanargument. 3.Whenanobjectisconstructedbasedonanotherobjectofthesameclass. 4.Whencompilergeneratesatemporaryobject. Itishowever,notguaranteedthatacopyconstructorwillbecalledinallthesecases,becausetheC++Standardallowsthecompilertooptimizethecopyawayincertaincases,oneexamplebeingthe returnvalueoptimization(sometimesreferredtoasRVO). 23.Whatisdifferencebetweenmalloc()/free()andnew/delete? 24.HowdoIoverloadanassignmentoperator? youcanoverloadtheassignmentoperator(=)justasyoucanotheroperatorsanditcanbeusedtocreateanobjectjustlikethecopyconstructor. Followingexampleexplainshowanassignmentoperatorcanbeoverloaded. #include usingnamespacestd; classDistance { private: intfeet;//0toinfinite intinches;//0to12 public: //requiredconstructors Distance(){ feet=0; inches=0; } Distance(intf,inti){ feet=f; inches=i; } voidoperator=(constDistance&D) { feet=D.feet; inches=D.inches; } //methodtodisplaydistance voiddisplayDistance() { cout<<"F: "< "< } }; intmain() { DistanceD1(11,10),D2(5,11); cout<<"FirstDistance: "; D1.displayDistance(); cout<<"SecondDistance: "; D2.displayDistance(); //useassignmentoperator D1=D2; cout<<"FirstDistance: "; D1.displayDistance(); return0; } 25.Whatisspecialtostaticdatamembersandmemberfunctionsinaclass? Aconstructorisaspecialmemberfunctionthatiscalledwheneveranewinstanceofaclassiscreated.Thecompilercallstheconstructorafterthenewobjecthasbeenallocatedinmemory,andconvertsthat"raw"memoryintoaproper,typedobject.Theconstructorisdeclaredmuchlikeanormalmemberfunctionbutitwillsharethenameoftheclassandithasnoreturnvalue. 26.whatisthedifferencebetween"new"and"operatornew"? operatornew isthelowestlevelallocationmechanism.Actualobjectsshouldbeallocatedwith new,whichtellsC++toactuallycreatetheobjectandsetupallitsnecessaryplumbing(superclassinformation,vtables,etc.),withoutwhichitisn'tcapableof being anobject. 27.Whatisthepurposeofkeyword“volatile”? olatileisahinttotheimplementationto avoidaggressiveoptimizationinvolvingtheobjectbecausethevalueoftheobjectmightbechangedbymeansundetectablebyanimplementation. 28.Whatisthepurposeofkeyword“mutable”? Itallowsthedifferentiationofbitwiseconstandlogicalconst.Logicalconstiswhenanobjectdoesn'tchangeinawaythatisvisiblethroughthepublicinterface,likeyourlockingexample.Anotherexamplewouldbeaclassthatcomputesavaluethefirsttimeitisrequested,andcachestheresult. 29.Whatispurevirtualfunction? orwhatisabstractclass? bstractClassisaclasswhichcontainsatleastonePureVirtualfunctioninit.AbstractclassesareusedtoprovideanInterfaceforitssubclasses.ClassesinheritinganAbstractClassmustprovidedefinitiontothepurevirtualfunction,otherwisetheywillalsobecomeabstractclass. 30.Canacopyconstructoracceptanobjectofthesameclassasparameter,insteadofreferenceoftheobject? No.Itisspecifiedinthedefinitionofthecopyconstructoritself.Itshouldgenerateanerrorifaprogrammerspecifiesacopyconstructorwithafirstargumentthatisanobjectandnotareference. 31.Whatisalocalclass? Whycanitbeuseful? localclassisaclassdefinedwithinthescopeofafunction--anyfunction,whetheramemberfunctionorafreefunction. Likenestedclasses,localclassesc
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- InterviewQuestion