Consider the following abstract data type for a String type:
class String {
private:
char* s;
int n;
public:
String(int length, char* c) // Create the string
int Strlen() {return n;} // Return the length of the string
void UpdateAt(int i, char c); s[i]= c;
}
char CharAt(int i) {
if(i>= 0 && i<=
Strlen()) return s[i];
}
};
(a)Explain the difference between deep and shallow copying of objects.[2
marks ]
Shallow copying is the default for
objects passed to functions,where both pointers point to the same
memory location.(1 mark)
deep copying copies the data pointed to,to a newly allocated
block of memory.
(1 mark)
[2 marks ]
(b)Implement the member function UpdateAt such that it will update
the character in the string at position i with character c if and
only if the string is long enough.[3 marks ]
A
sample definition of UpdateAt follows:
void UpdateAt(int i, char c) {
if(i>= 0 && i< Strlen() ) s[i]= c;
}
And the following marking scheme should be used:
Testing i>= 0);(1 mark)
And that i< Strlen() (note the use of Strlen is important;(1
mark)
Updating the character if the guard is safe.(1 mark)
[3 marks ]
(c)Write a constructor function for the String class which performs
a deep copy of the object.You may not use any library functions.[5
marks ]
A sample constructor definition follows:
String::String(const String& s)
{
n= s.Strlen();
s= new char[n];
for(int i= 0; i< n; i++)
UpdateAt(i, s.CharAt(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 String (1 mark)
Declaring a suitable iterative structure,bound by n (1 mark)
Assigning the indexed element on each iteration,using the correct
member
functions.(1 mark)
[5 marks ]
(d)Write a function,called Reverse the signature of which is given
below,which takes a String object and returns a new String which is
the reverse of the original object. You may not use any library functions.[5
marks ]
A sample definition of Reverse follows:
String Reverse(String s)
{
String t;
int i= 0;
int j= s.Strlen();
while(i< s.Strlen()) {
t.UpdateAt(j, s.CharAt(i));
i++;
j--;
}
return t;
}
And the following marking scheme should be used:
Declaring a local String variable;(1 mark)
Declaring and initialising local ariables i and jj (1 mark)
Declaring a suitable iterative structure,bounded by the length
of the string;
(1 mark)
Updating the indexed elements on each iteration using the correct
member
functions;(1 mark)
Returning the reversed String (1 mark)
[5 marks ]
|