Search code examples
c++destructordeep-copy

Deep Copy is not working


in the follwing example am doing deepcopy, every thing works fine but when the obj2 goes out of scope, destructor is calling and it is getting crash inside destructor so please help what is wrong with my code:

#include "stdafx.h"
#include <windows.h>
#include <stdlib.h>
#include <iostream>
#include <conio.h>
using namespace std;

class ClassA
{
     private:
        char *str;
        int id;

     public :
        ClassA(int x, char *s)
        {
            int len = strlen(s)+1;
            str = new char[len];
            id = x;
            strcpy(str, s);
        }
       ~ClassA()
        {
            delete [] str;
        }
        ClassA(ClassA &obj)
        {
            id = obj.id;
            int len = strlen(obj.str);
            str = new char[len] + 1;
            strcpy(str, obj.str + 1);
        }
        void disply()
        {
            cout << id << " " << str << endl;
        }  
 };

 int main()
 {
   ClassA Obj1(5, "hello");
   {
    ClassA Obj2 = Obj1;
    Obj2.disply();
   }
   Obj1.disply();
    return 0;
 }

Solution

  • You need an assignment operator. You need to write your copy constructor like this

    ClassA(const ClassA &obj)
    

    The const is very important.

    Plus you have several bugs

            int len = strlen(obj.str);
            str = new char[len] + 1;
            strcpy(str, obj.str + 1);
    

    should be

            int len = strlen(obj.str);
            str = new char[len + 1];
            strcpy(str, obj.str);