=========================preview======================
(COMP151)comp151_01s_final_sol.pdf
Back to COMP151 Login to download
======================================================
COMP151{Lectures1,2,3 FinalExam{May23,2001 ExamDuration{3hours
Name: E-mail: StudentNo: Lecture/LabSection:
Answerallofthefollowingquestions.Doyourworkontheexampaper. Ifnecessary,youmaywriteonthebackofthesheets. Thelastthreeblanksheetsofthisexammaybetorno.andusedasscratchpaper.

1.(5points)Considerthefollowingclassandfunctionde.nitions:
#include.iostream.
classB
{public:

virtualvoiddisplay()
{cout.."DisplayingB"..endl.}
}.

classD:publicB
{public:
virtualvoiddisplay()
{cout.."DisplayingD"..endl.}
}.

voidf(B&b)
{b.display().}

voidg(Bb)
{b.display().}


Now,assumethefollowingobjectdeclarations:
Dd.
Bb.d.
B*p.&d.


Assumetheabovede.nitionsanddeclarations. Foreachofthe.vefunctioncallslistedbelow,writedowntheoutputgenerated.1pt
each
(a)b.display().DisplayingB
(b)p-.display().DisplayingD
(c)f(d).DisplayingD
(d)g(d).DisplayingB
(e)f(b).DisplayingB

2.(10points)InthisquestiontherearetwoclassesBandD.Theirclassde.nitionsare containedin.leD.h.Thereisalsoa.leD.cppcontainingtheimplementationofD's memberfunctionsthatyouwillhavetowrite.
//******************fileD.h********************************
classB
{public:

B(intval){x.val.}
intget_x(){returnx.}
virtualvoidreturn_x().0.

private:
intx.

}.
classD:publicB
{public:
D(intval). //setstheB::xmemberofDtoval
virtualvoidreturn_x().//printstheB::xpartofD

}.
//******************EndofD.h*******************************


Asanexample:whenthefollowingdriveriscompiledtogetherwithD.cppandthen run,theappendedoutputisprinted.
#include"D.h"
voidmain()
{Dd(5).

d.return_x().
}
OUTPUT
B::xmember.5
3

Toanswerthisquestionyouneedtowritethe.leD.cppthatcontainstheimplemen-tationsofD'smemberfunctions.
//******************fileD.cpp*************************
#include.iostream.
#include"D.h"

//WritetheimplementationofD'sconstructorbelowthisline

(7pts)
D::D(intval):B(val){}.

//Note:Thisistheonlywayofwritingtheconstructor.
//Itisnotpossibletowritesomethingsuchas
//D::D(intval):{B::x.val}.

//WritetheimplementationofD'sreturn_x()belowthisline

(3pts)
voidD::return_x(){cout.."B::xmember."..get_x()..endl.}

//Note:SincexisprivateinB,get_x()mustbeused
//toaccessitsvalue.

4 3.(15points)Thisquestionconcernsthefollowingpieceofcode:

1.#include.iostream.
2.classB
3.{public:
4.
B(){x.newint.*x.5.

5.
~B(){deletex.

6.
voiddisplay(){cout.."*x.


7.private:
8. int*x.
9.}.
10.classD:publicB 11.{public:
12.
D(){y.newint.*y.3.

13.
~D(){deletey.

14.
voiddisplay(){cout.."*y


15.private:
16. int*y. 17.}.
18.voidmain()
19.{Dd.
20.
d.display().

21.
cout.."*******1*******"..

22.
B*p.newD.

23.
p-.display().

24.
cout.."*******2*******"..

25.
deletep.

26.
cout.."*******3*******"..


27.}
cout.."CB"..endl.} cout.."DB"..endl.}
"..*x..endl.}
cout.."CD"..endl.} cout.."DD"..endl.}
."..*y..endl.}
endl.
endl.
endl.
5 (a)Writethecomplet