December 1999
OP216 : OBJECT ORIENTED PROGRAMMING

QUESTION 5

Total Marks: 15 Marks

Click here to access other questions

SUGGESTED SOLUTIONS
Solutions and allocated marks are indicated in green.
Return to
Question 5

Consider the following abstract data type declaration for an IntegerList type:

class IntegerList {
private:
int*s;
int n;
public:
IntegerList(int m,int*t); //Copy n characters from t to s
int Length(){return n;} //Return the length of the list
void UpdateAt(int i,int c) {
if(i>=0 &&i<=length())s [i ]=c;
  } //Update the element at index i with element c
  int ElementAt(int i){
    if(i>=0 &&i<=length())return s [i ];else return 0;
  } //Return the element at index i };
};      

 

(a)

Explain the difference between deep and shallow (or member-wise) copying of objects.

•A shallow copy is the default copy for objects passed by value to a function;
(1 mark)
•Where both pointers point to the same memory location;(1 mark)
•A deep copy copies the data pointed to,to a newly allocated block of memory.
(1 mark)

 

[3]
(b)

Write a constructor function for the IntegerList class which performs a deep copy of the object.You may not use any library functions.

A sample definition of the constructor function IntegerList follows:

IntegerList::IntegerList(const IntegerList&p)
{
  n=p.n;
s=new int [n ];
for(int i=0;i<n;i++)
s [i ]=p.s [i ];
}  

And the following marking scheme should be used:
•A correct signature with const references;(1 mark)
•Assigning the length of the new object;(1 mark)
•Allocating space for the new IntegerList ;(1 mark)
•Declaring a suitable iterative structure;(1 mark)
•Bound by the source IntegerList length;(1 mark)
•Assigning the indexed element on each iteration.(1 mark)
[6 marks ]

 

[6]
(c)

Write a function Reverse ,the signature of which is given below,which takes an IntegerList object and returns a new IntegerList which is the reverse of the original IntegerList .You may not use any library functions.
IntegerList Reverse(IntegerList s);

A sample definition of Reverse follows:

IntegerList Reverse(IntegerList q)
{
  IntegerList p=q;
int i=0;
int j=q.Length();
while(i<q.Length()){
 


p.UpdateAt(j, q.ElementAt(i));
i++;
j--;
}
  return p;
}  

And the following marking scheme should be used:
•Declaring a local IntegerList variable;(1 mark)
•Declaring and initialising local variables i and jj ;(1 mark)
•Declaring a suitable iterative structure;(1 mark)
•Bound by the IntegerList length conditions;(1 mark)
•Updating the indexed elements on each iteration;(1 mark)
•Returning the reversed IntegerList .(1 mark)
[6 marks ]

[6]