0

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;
 }
nagaradderKantesh
  • 1,672
  • 4
  • 18
  • 30

2 Answers2

3

You need to follow the rule of three and provide an assignment operator. But this line looks suspect:

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

You probably mean

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

Once you are done fixing your class, you can use std::string instead of char*.

class ClassA
{
 private:
    std::string str;
    int id;
 public:
  // no copy constructor or assignment operator or destructor required
};
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
0

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);
john
  • 85,011
  • 4
  • 57
  • 81