Question

I use following function to fill array of class 'SolidSphere' with spheres:

SolidSphere *createSpheres()
{
    SolidSphere *spheres[numSpheres];
    for (int i = 0; i < numSpheres; i++)
        spheres[i] = new SolidSphere(1, 12, 24);

    return *spheres;
}

Now I want to use createSpheres' return value inside another function:

void display()
{
    for (int i = 0; i < numSpheres; i++)
        spheres[i]->draw(posX,posY,posZ);
}

However, inside display() 'spheres' appears as undefined identifier. How do I proceed? Thanks for any help you can give.

Was it helpful?

Solution

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.

OTHER TIPS

You are creating array of pointers. Although the SolidSphere objects are getting created on heap, the array itself is still on the stack and its scope is local to the function createSpheres. So it gets destroyed once the execution comes out of the function.

You need to create your array too on heap:

SolidSphere **spheres = new SolidSphere*[numSpheres];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top