August
1999 QUESTION 5 Total Marks: 20 Marks |
Click here to access other
questions
SUGGESTED SOLUTIONS |
(a) | Explain what is meant by a copy constructor, and give an example of when such an operation is performed. | [3] |
|
||
(b) | Consider the class String, which contains a
character array, and an integer, reference_counter. class String { (i) Define a function strcmp, which takes two objects String by reference, and returns 0 if the character array stored in each object is the same, and -1 otherwise. You may not use any standard library functions. (ii) Implement the member function update_at, such that it will update the character at position x with the character specified by y, if and only if the string is long enough. (iii) Write a function replace, which takes a reference to a string s, and two char parameters x and y, and will replace all occurrences of the character x with the character y. (iv) Implement an overloading of the operator != that takes two strings by reference, and returns 1 if the strings differ, and 0 if they are the same.
|
[4]
[3]
[4]
|
(i)
A sample definition of strcmp follows: int strcmp(String& s, String& t) { int i; for(i= 0; i< s.length( ); i++) if(s.char_at(i) != t.length( ); i++) return -1; return (s.length( )==
t.length( ) ? 0 : -1);
|
||
(ii) A sample definition of update_at follows: void String : : update_at(int x, char y) { if(length( ) >= x) my-string[x-1]= y; }
|
||
(iii) A sample definition of replace follows: void replace*String& s, char x, char y) { int i; for(i= o; i< s.length( ); i++) if(s.char_at(i)== x) s.update_at(i, y) ; }
|
||
(iv) A sample definition of != follows: int operator != (String& s, String& t) { int i; for(i= 0; i< s.length( ); i++) if(s.char_at(i) != t.char_at(i) ) return 1; return (s.length( ) == t.length( ) ? 0 : 1);
|