I am getting this error when i define a destructor in the class and try to use copy assignment constructor. Without destructor, copy assignment constructor works just fine. Can someone explain to me what could be the issue?
"terminate called after throwing an instance of 'std::bad_array_new_length' what(): std::bad_array_new_length"
Below is the code. Some of the class functions and constructors have not been pasted to avoid too much code.
class myvector
{
int size;
int *elem;
public:
// constructor
myvector(int size)
{
this->size = size;
this->elem = new int[size];
}
// copy constructor
myvector(const myvector &ob)
{
cout<<"copy constructor\n";
try{
elem = new int[ob.size];
}catch(bad_alloc xa)
{
cout<<"Allocation failure. Please check heap memory\n";
}
for(int i=0; i<ob.size; i++)
elem[i] = ob.elem[i];
}
// copy assignment constructor
myvector& operator=(const myvector &ob)
{
cout<<"copy assignment constructor\n";
if(this != &ob)
{
delete[] this->elem;
this->size = ob.size;
this->elem = new int[ob.size];
for(int i=0; i<ob.size; i++)
this->elem[i] = ob.elem[i];
}
return *this;
}
void update(int idx, int val)
{
elem[idx] = val;
}
int get(int idx)
{
return elem[idx];
}
int getSize()
{
return this->size;
}
~myvector()
{
cout<<"destructor \n";
if(elem!=NULL)
delete[] elem;
}
};
int main()
{
myvector ob1(5);
myvector ob2(6);
myvector x = ob1;
myvector y = ob1;
ob2.update(0, 15);
// copy assignment constructor will be invoked
ob2 = x;
cout<<ob2.get(0)<<endl;
cout<<x.get(0)<<endl;
cout<<y.get(0)<<endl;
return 0;
}