0

I am creating a class that works similar to the string class. I am in a starting stage doing some experiments.

Assume all header files are added

class String
{
      public: 
          int len; 
          char *str = NULL;                                                                       

      // Default constructor 
      String()
      {                                             
           len = 0;
           str = new char[1];             
           str[0] = '\0';
           printf("New memory: %p\n", str);
      }

    // Copy constructor
    String(const char *ch)
    {
        len = strlen(ch);  

        if (str != NULL)
        {
            printf("Old memory: %p\n", str);
            delete str; 
            printf("Deleted...\n");               
        }

        str = new char[len + 1];
        printf("New memory: %p\n", str);

        for (int i = 0; i <= len; i++)
            str[i] = ch[i];
    }
};


int main()
{
    String msg;

    std::cout << msg.len << std::endl;
    std::cout << msg.str << std::endl;

    msg = "Hello";
    std::cout << msg.len << std::endl;
    std::cout << msg.str << std::endl;
}

When I create a String object 1 byte of memory is allocated to store string and initialises with \0 on line String msg;

When copy constructor is called on line msg = "Hello"; it first checks for any previous allocation of memory and to avoid memory wastage it will delete that and recreates a new memory block.

The issue is when copy constructor is called line if (str != NULL) is not getting executed. It should execute because str is allocated a byte of memory earlier in default constructor and it is not NULL.

What may be the thing that I missed out?

Next-93
  • 97
  • 1
  • 7
  • 3
    That's not a copy constructor. That's a constructor that takes a `const char*`. A copy constructor would have the signature `String(const String& other)` – JohnFilleau May 09 '20 at 14:10
  • Doesn't C++ (including its various libraries) have more than enough string classes already? Why create yet another one? – Jesper Juhl May 09 '20 at 14:10
  • When you call a non-default constructor for a class, the default constructor is not called beforehand. When you enter `String(const char*)` your `String` is in the same state as if you just entered `String()`. That means `str == NULL`. Also use `nullptr` instead. – JohnFilleau May 09 '20 at 14:12
  • 1
    @JohnFilleau We have an answer section for answers. Thanks. – Asteroids With Wings May 09 '20 at 14:16
  • @JesperJuhl Learning? Practice? It's a pretty common exercise, is it not? – Asteroids With Wings May 09 '20 at 14:16
  • @AsteroidsWithWings but your answers are much better than mine and I haven't had my second cup of coffee yet. (you're right though I'm bad about that) – JohnFilleau May 09 '20 at 14:24
  • *What may be the thing that I missed out?* -- The [rule of 3](https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three). Especially read the **Managing Resources** section of that link. – PaulMcKenzie May 09 '20 at 14:40
  • @JohnFilleau ok sorry my mistake I miss understood it as copy constructor. Then what would be the better name for that? A conversion constructor as mentioned by Asteroids With Wings – Next-93 May 09 '20 at 19:56
  • @Jesper Juhl. Yes we have. It is purely to understand the things and how it works by some simple experiments – Next-93 May 09 '20 at 19:59

1 Answers1

2

Your code does this:

  • Default-construct a String "A"
  • Convert-construct a temporary String "B" from the expression "Hello"
  • Copy-assign "B" to "A"

The assignment does not invoke the constructor on "A". You only get one construction per object.

Unless you specify otherwise (with delegating constructors), your default constructor is not invoked before the "copy constructor" (or a conversion constructor like yours) is run.

So this:

It should execute because str is allocated a byte of memory earlier in default constructor and it is not NULL.

is wrong.

String(const char *ch) needs to allocate.

Also, because you're performing assignment, you're going to need to implement a copy assignment operator to make that safe.

Asteroids With Wings
  • 17,071
  • 2
  • 21
  • 35