I have a project in which I created an abstract class that represents a shape. I have a circle and a quad inherited from a shape and square inherited from a quad.
Finally I have a class called allShapes
that has a polymorphic array of Shape **
pointers and its size.
I need to implement the + operator, which receives an allShapes
object and returns a new allShape
with all elements located at this and other.
When I copy the part of this, the copy is done correctly but when I copy the parts from other I think it does not copy because when the function is finished when it comes to destruction I jump to an error that I am trying to delete blank content. what did I do wrong?
allShapes allShapes::operator+(const allShapes & other) const
{
allShapes newS;
newS._size = (this->getSize() + other.getSize());
int k = 0;
newS._arr = new Shape*[newS.getSize()];
for (int i = 0; i < this->getSize(); i++)
{
newS._arr[i] = this->_arr[i];
}
for (int j = this->getSize(); j < newS.getSize(); j++)
{
newS._arr[j] = other._arr[k++]; //i think here is the problem
}
return newS;
}
edit: i add the others methods that someone asks:
allShapes::allShapes(const allShapes & other) //copy constructor
{
this->_size = other.getSize();
this->_arr = new Shape*[other.getSize()];
for (int i = 0; i < other.getSize(); i++)
{
this->_arr[i] = other._arr[i];
}
}
allShapes::~allShapes()//destructor to all elements
{
if (this->_arr != NULL)
{
for (int i = 0; i < this->_size; i++)
{
delete this->_arr[i];
}
delete[] this->_arr;
}
}
class allShapes {
private:
Shape ** _arr;
int _size;