Hello, i've got an assigment that requires me to overload some operators and add some objects together.
I will show the code and explain as good as I can.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
void SArray::operator+= (const SArray &obj)
Sphere * tmp_arr;
tmp_arr = new Sphere[obj.antalobjekt+this->antalobjekt]; //antalobjekt = //Gets amount of elements in the arrays.
//arraystorlek = size of the array.
//get_antal = same as antalobjekt. Just a getter.
m_arr = tmp_arr;
this->antalobjekt = this->antalobjekt+obj.antalobjekt;
//plussa två SArray
Adds a object to another one, using this operator as a base for the + operator.
I think i need to delete somewhere in the operators, i don't really know where.
Anyways, more code.
1 2 3 4 5 6 7 8 9 10
SArray& SArray::operator= (SArray &SA) // i = SA; i.=(SA);
if (this == &SA)
this->set_arraystorlek(SA.get_arraystorlek()+100); //Set size to //arraysize + 100
memcpy(m_arr, SA.m_arr, (antalobjekt-1)*sizeof(Sphere));
If line 6 of the SArray::operator+= snippet sets the value that get_antal() retrieves on line 9, you have a problem. You should only be copying the number of objects originally in *this. Also, I don't see any memory deallocated here. Presumably some was previously allocated that should be deallocated or there wouldn't be any objects to copy from *this.
In SArray::operator=, the use of memcpy for class objects is wrong. I don't see any allocation or deallocation of memory here. Is that accomplished in set_arraystorlek?