Pete42
Pete42

Reputation: 906

Finding problem with class copy construction

I have a problem with one of my c++ assignments. Its more of a theory question. Here is the code:

//a class implementation
class IntArrays {
public:
   IntArrays(int n): data(new int[n]), size(n) { }
   ~IntArrays() { delete[] data; };
   const int& operator[](int n) const
      { return data[n]; }

   IntArrays(const IntArrays& ar):
      data(new int[ar.size]),
      size(ar.size) {
      std::copy(data, data + size, ar.data);
   }

private:
   int* data;
   int size;
};

//a driver
int main()
{
    IntArrays a(100);
    IntArrays b = a;   // Problem!
      return 0;
}

In 1-2 sentences, explain why the second line of the driver program is problematic.

I really don't know what the error is with the second line of the driver because when I run it its fine. At first I thought it was because the = operator was not overloaded but the IntArrays b = a is using the copy constructor so thats not it. Im completely baffled, please help. This is going to bother me so much if I don't get an answer.

thanks in advance.

Upvotes: 1

Views: 77

Answers (1)

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

You're copying the wrong way.

std::copy(data, data + size, ar.data);

Should be:

std::copy(ar.data, ar.data + size, data);

Upvotes: 4

Related Questions