=========================preview======================
(COMP151)midterm_s2005.pdf
Back to COMP151 Login to download
======================================================
COMP 151: Object-Oriented Programming
Spring Semester 2005
Midterm Examination
Thursday, March 17, 2005
7:30pm C 10:00pm

This is a CLOSED-BOOK-CLOSED-NOTES exam consisting of six (6) problems. Follow the instructions carefully. Please write legibly in the boxes provided. Any space outside the boxes is for sketching and will not be graded. Keep the exam booklet stapled. Write legibly. You may use pencil to answer the questions.
Name: KEY
E-mail:
ID:
LAB:
Problem Points Score
1 OBJECT INITIALIZATION 5
2 MEMORY MANAGEMENT 7
3 INHERITANCE: I 4
4 INHERITANCE: II 7
5 OBJECT-ORIENTED MINI-PHOTOSHOP 18
6 INHERITANCE: III 29
Total 70

1 Object initialization (5 POINTS)
Consider the following class interface and implementation .les, queue.h and queue.cpp, respectively, for a user-de.ned class Queue.
// queue.h

#ifndef QUEUE_H
#define QUEUE_H

struct Node;

class Queue
{
public:

Queue(int size); // constructor

private:
int qsize; // maximum number of items in Queue
int nitems; // current number of items in Queue
Node* head; // pointer to head of Queue
Node* tail; // pointer to tail of Queue

};

#endif

// queue.cpp

#include "queue.h"

struct Node

{
double item;
Node* next;

};

Queue::Queue(int size)

{
qsize = size;
nitems = 0;
head = tail = 0;

}

Suppose we want to change the private member variable qsizeof Queueto a constant named QSIZE.
(a) (3 POINTS) Show all change(s) that you should make to the .le(s) for the class to work properly.
Answer:
The following changes should be made:
i. Change int qsize in queue.hto const int QSIZE.
ii. Change the constructor de.nition of Queue::Queue()to
Queue::Queue(int size) : QSIZE(size)
{
nitems = 0;

head = tail = 0;
}

(b) (2 POINTS) Explain why initialization of the constant QSIZE cannot be done inside the class interface in queue.h.
Answer:
It does not make sense to initialize the constant value in the class interface because we have to initialize the constant value for each object which can only be done during its creation via a constructor.

2 Memory management (7 POINTS)
Consider the following program:
#include <cstring>
using namespace std;

class Employee
{
public:

Employee(const char* firstname, const char* lastname);

private:
char* _firstname;
char* _lastname;

};

Employee::Employee(const char* firstname, const char* lastname)

{
_firstname = new char[strlen(firstname)+1];
strcpy(_firstname, firstname);
_lastname = new char[strlen(lastname)+1];
strcpy(_lastname, lastname);

}

void process()

{
Employee* e; // (A)
Employee f("Arthur", "Li"); // (B)
e = new Employee("Donald", "Tsang"); // (C)
delete e; // (D)

}

int main()

{
// code omitted
process(); // (E)
// code omitted

return 0;
}

(a) (2.5 POINTS) The program shows a bad practice in memory management. Add some code to the class de.nition to correct the problem.