The reason the display
function does not see the spheres
array is that spheres
is local to createSpheres
; no other function will be able to see it.
There are several issues with your code:
- You are creating an array of pointers to
SolidSphere
, but your function returns a single pointer to sphere.
- If you try returning the array as-is, the caller would not be able to use it, because the memory would be gone (it's in local storage).
If you wish to return a group of SolidSphere
objects, the best approach would be to return a vector
of them. If you must return a collection of pointers, you should use smart pointers (e.g. unique_ptr<SolidSphere>
) instead of regular pointers.
If you are doing this as a learning exercise and you must use plain pointers for your arrays, you need to allocate the array dynamically, like this:
SolidSphere **createSpheres()
{
SolidSphere **spheres = new SolidSphere*[numSpheres];
for (int i = 0; i < numSpheres; i++)
spheres[i] = new SolidSphere(1, 12, 24);
return spheres;
}
Now you can call createSpheres()
from display
, like this:
void display()
{
SolidSphere **spheres = createSpheres();
for (int i = 0; i < numSpheres; i++) {
spheres[i]->draw(posX,posY,posZ);
}
// Now you need to free the individual spheres
for (int i = 0; i < numSpheres; i++) {
delete spheres[i];
}
// Finally, the array needs to be deleted as well
delete[] spheres;
}
If createSpheres()
and display()
are members of the same class, you could make spheres
a member variable of that class. Then you could make createSpheres
a void
function, drop the declaration and the return, and use spheres
in the display
, because it is a member variable now.