Interview Question: Mystic Constructions

Sample Question #98 (programming – C++)

Suppose a String class has the following private members:

class String
{
   private:
      char * str;
      int len;
   //… rest of definition
};

1) What’s wrong with this default constructor?

String::String() {}

2) What’s wrong with this constructor?

String::String(const char * s)
{
   strcpy(str, s);
   len = strlen(s);
}

[Taken from review question 12.1 in Prata, C++ Primer Plus, 5th ed.]

Advertisements
This entry was posted in Sample Qs. Bookmark the permalink.

3 Responses to Interview Question: Mystic Constructions

  1. Brett says:

    ANSWER
     
    1) str is a pointer, so this constructor leaves the str pointer uninitialized. (Okay, then, what should you do to correct this error?)
     
    2) Really the same as #1 – you cannot copy a string without allocating space to store it.

  2. Marcos Alberto says:

    You are right, that is true unless you specify with a compiler switch to initialize all variables to 0, this is useful for such class of mistakes.

  3. Wu Chao says:

    I need to work out the problems after each chapter in this book. The book is so thick.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s