Chapter 12

1: Suppose a String class has the following private members:
class String
{
private:
    char * str;    // points to string allocated by new
    int len;       // holds length of string
//...
} ;
  1. What's wrong with this default constructor?

    String::String() { }
    
  2. What's wrong with this constructor?

    String::String(const char * s)
    {
        str = s;
        len = strlen(s);
    }
    
  3. What's wrong with this constructor?

    String::String(const char * s)
    {
        strcpy(str, s);
        len = strlen(s);
    }
    
A1:
  1. The syntax is fine, but this constructor leaves the str pointer uninitialized. The constructor should either set the pointer to NULL or use new [] to initialize the pointer.

  2. This constructor does not create a new string; it merely copies the address of the old string. It should use new [] and ...

Get C++ Primer Plus, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.