August 1999
OP216 : OBJECT ORIENTED PROGRAMMING

QUESTION 5

Total Marks: 20 Marks

Click here to access other questions

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

(a) Explain what is meant by a copy constructor, and give an example of when such an operation is performed. [3]
  • A copy constructor is one which takes a reference;
  • To an object of the same type;
  • It is called when a variable is initialized using another of the same type;

 

(b) Consider the class String, which contains a character array, and an integer, reference_counter.

class String {
public:
     int length();       //Return the length of the string data
     char char_at(int);  //Return the character at the given position in data
     void update_at(int, x char y);   // Update the character at the given                                                    // position in data private:
     char* my_string;
     int reference_counter = 0;
} ;

(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]


[6]

(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);
}