April 1999
OP216: OBJECT-ORIENTED PROGRAMMING

QUESTION 1 (Compulsory)

Total Marks: 20 Marks

Click here to access other questions

GRADE A
Sample student's solutions are indicated in green.
Return to Question 1

 

(a) State two components of an Abstract Data Type in object-oriented programming. [2]
Two components of an Abstract Data Type:
  1. Attributes, which define its structure.
  2. Methods, which define the operations that can be performed on the Abstract Data Type.

 

(b) Explain the difference between a class and an object in C++. [2]
Class
An abstract data type. It contains attributes and methods which define its structure and operations respectively.

Object
An instance of a class.

 

(c) Explain the purpose of a pure virtual function in C++. Give an example declaration of one. [3]
Pure virtual functions allow the association of a name to a function at run-time, rather than compile-time. This is known as dynamic binding.

Example:
virtual Example() = 0;

 

(d) Consider the following program fragment:

class Person {
private:
   ...                    // Some private definitions
public:
   Person();               // Constructor
   Person(const Person &); // Copy Constructor
...
};

class Telephone_book {
private:
   int entries; // The number of people in the book
   Person book [10000];  // A book is an array of
                         // 10000 persons.
public:
  ...
}

 

(i) Explain what a deep copy of objects is in C++ and give an example of when it is most likely to be used. [2]
(ii) Give the implementation of a deep copy constructor for the Telephone_book class. [5]
(i) A deep copy of an object is when a copy constructor is written, to override the default constructor, that creates a copy of the data by allocating it a new data block of memory. This results in separate copies of data for the two objects.
It is most likely to be used when a copy of an object is being made through a copy constructor.

(ii)
Telephone_book::Telephone_book (Telephone_book& a)
{  int i;
   entries = a.entries;
   for (i=0;i<10000;i++)
      book[i] = a.book[i];
}

 

(e) Consider the following function in C++;

void foo(int *y, int *z) {
   int x;
   cin >> x;
   if(x>=0) {
      (*y)++;
      (*z) += x;
       cout << "*y = " << *y << ";" << " *z = " << *z
            << endl;
       foo(y,z);
   }
}

 

(i) Trace the output of the function foo(&a, &b), assuming that int a = b =0 and the following values are input for x: 1,4,2,1,-9. [4]
(ii) Explain the behaviour of foo. [2]
(i) Ouput:
*y = 1;  *z = 1
*y = 2;  *z = 5
*y = 3;  *z = 7
*y = 4;  *z = 8

(ii) The behvaiour of foo exhibits that it increments the contents of y and that it sums the values entered of x, until the first negative value of x.