Question

I have a class that contains an array of another class called Sphere. Right now i am not sure why one part of code is generating an error.

.H file

sphere* list;
int listlen;
void add(sphere x);
sarray operator +(const sarray& arrayone);

.Cpp

sarray::sarray()
{
listlen = 0;
list = new sphere[200000];
}

sarray::~sarray()
{
delete [] this->list;
}

void sarray::add(sphere x) // Function for adding spheres to the list.
{
    listlen++;
list[listlen-1] = x; 
}   

void sarray::operator = (const sarray& arrayone)
{
  this -> list = NULL;
  for(int i = 0; i < arrayone.listlen; i++)
  {
      this -> add(arrayone.list[i]);
  }
}

sarray sarray::operator +(const sarray& arrayone)
{
sarray temparray;

for(int i = 0; i < arrayone.listlen; i++) // add all the elements from the first array to the temporary one
{
    //sphere temp = arrayone.list[i];
    temparray.add(arrayone.list[i]);
}

for(int j = 0; j < this -> listlen; j++)// add all the elements from the second array to the temporary one
{
    temparray.add(list[j]);
}

return temparray;
}

The sphere class got a member variable called "Radius" which when i try to compare like this

float a = 10;
for(int i=0; i > this->listlen;i++)
  if(this->list[i].Radius > a) //<-- Can read the values

Works fine, but when change this part of the code

float a = 10;
sarray temparray = arrayone + *this;
for(int i = 0; i < temparray.listlen; i++)
  if(temparray.list[i].radius > a) // Error comes here!

"Unhandled exception at 0x00138503: Access violation reading location"

while this doesent. I guess the problem is in the Add/operator function but i cant find it.

Was it helpful?

Solution 2

OK, having looked at the destructor, you have a pointer to sphere in your sarray and has a destructor to destroy the pointer. This is all good except you haven't defined your own copy constructor which means the default copy constructor is used. In the function operator+ where you return temparray, a copy of the local copy is returned. The default copy constructor is called to create the copy. Then the local one will be destructed. Now the returned sarray copy's list will point to invalid data. You need to define your own copy constructor to make a deep copy of the list pointer.

OTHER TIPS

The following part looks problematic:

void sarray::add(sphere x) // Function for adding spheres to the list.
{
list[listlen-1] = x; 
} 

you should rather have something like this

void sarray::add(sphere x) // Function for adding spheres to the list.
{
list[listlen++] = x; 
} 

Also you should better have some error checking in add method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top