C++InterviewQuestion.docx

上传人:b****6 文档编号:6131531 上传时间:2023-01-04 格式:DOCX 页数:12 大小:44.64KB
下载 相关 举报
C++InterviewQuestion.docx_第1页
第1页 / 共12页
C++InterviewQuestion.docx_第2页
第2页 / 共12页
C++InterviewQuestion.docx_第3页
第3页 / 共12页
C++InterviewQuestion.docx_第4页
第4页 / 共12页
C++InterviewQuestion.docx_第5页
第5页 / 共12页
点击查看更多>>
下载资源
资源描述

C++InterviewQuestion.docx

《C++InterviewQuestion.docx》由会员分享,可在线阅读,更多相关《C++InterviewQuestion.docx(12页珍藏版)》请在冰豆网上搜索。

C++InterviewQuestion.docx

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

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 经管营销 > 生产经营管理

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1