0

My assignment is to "mimic" vector using class and dynamic array. However, my program behaved unpredictably whenever I use the copy constructor. Can anyone explain to me what I did wrong here? (please explain in details because I'm new to programming).

#include<iostream>
using namespace std;

class VectorDouble
{
public:
    VectorDouble(int size);
    VectorDouble(const VectorDouble& source);
    ~VectorDouble();
    friend ostream& operator << (ostream& outs, const VectorDouble& v);//this function is to output the entire vector to outs stream
    void push_back (double value); //mimics the function push_back 
private:
    double *ptr;
    int count, max_count;
};

int main()
{
    VectorDouble my_vec(2);
    my_vec.push_back(4.1);
    VectorDouble your_vec(my_vec);
    cout<<my_vec;
    cout<<your_vec;
    return 0;
}

VectorDouble::VectorDouble(int size):count(size),ptr(new double[count]),max_count(size+2)
{
    for (int i=0;i<size;i++)
    {
        ptr[i]=0.0;
    }
}
VectorDouble::VectorDouble(const VectorDouble& source)
{
    count=source.count;
    max_count=source.max_count;
    ptr=new double[count];
    for (int i=0;i<count;i++)
    {
        ptr[i]=source.ptr[i];
    }
}
VectorDouble::~VectorDouble()
{
    delete []ptr;
}
ostream& operator << (ostream& outs, const VectorDouble& v)
{
    for (int i=0;i<v.count;i++)
    {
        cout<<v.ptr[i]<<" ";
    }
    return outs;
}
void VectorDouble::push_back (double value)
{
    VectorDouble temp(0);
    if (count==max_count)
    {
        temp.max_count=max_count*2;
    }
    temp.count=count+1;
    temp.ptr=new double[temp.count];
    for (int i=0;i<count;i++)
    {
        temp.ptr[i]=ptr[i];
    }
    temp.ptr[temp.count-1]=value;
    delete [] ptr;
    count=temp.count;
    max_count=temp.max_count;
    ptr=new double [count];
    for (int i=0;i<count;i++)
    {
        ptr[i]=temp.ptr[i];
    }
}
CuriousAlpaca
  • 131
  • 1
  • 7

0 Answers0