Diogo Neiss
Diogo Neiss

Reputation: 117

Create an array of pointers of a superclass to heap allocate inheritted classes

Basically, I want to work with an array of pointers of a superclass and use them for subclasses.

I have a code that manipulates geometric forms. It's a "geometric forms" superclass, consisting of virtual methods and static ints.

Later in the code, I create inherited classes (circles, squares..), complementing the application.

I want to create an array of "geometric forms" pointer and pass the i'th item (index based on static attribute) to a specific sub-function, based on a switch case, responsible for methods for that geometric figure, with that i'th pointer.

Example: I want to work with squares, so I pass a menuSquares(geometricFroms *array[foo::getStatic()]){}...

Inside that function, I want to do:

ptrPassed = new Circle();

How can I do that?

I tried using a generic int pointer instead of a superclass type:

Class GeomFig {};

Class Circle : public GeomFig
{};

int main(){

    GeomFig *arrayPtrs[100];

    // selection of which shape the user wants to use
    // ...

    menuSquares(arrayPtrs[GeomFig::getStatic()]) {}...

}

// code def
menuSquares(GeomFig* &geomPtr)
{
    geomPtr = new Circle();
}

Upvotes: 2

Views: 52

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596437

Your menuSquares() is taking its GeomFig* parameter by value, so the parameter is local to menuSquares() only and anything assigned to it inside of menuSquares() will not be seen by the caller.

If you want the caller to see the new pointer value, you need to pass the pointer by reference instead:

void menuSquares(GeomFig* &geomPtr)
{
    geomPtr = new Circle();
}

Otherwise, have menuSquares() return the desired pointer in its return value instead of using an output parameter:

GeomFig* menuSquares()
{
    return new Circle();
}

...

arrayPtrs[GeomFig::getStatic()] = menuSquares();

Upvotes: 1

Related Questions