Neat way to inizialize array of a base class with addresses of newly constructed derived objects

Viewed 42

I want to initialize an array of pointers to a base class through an initializer list, giving it addresses of objects of derived classes.

King king{square};
Queen queen{square};
Rook rook{square};

Piece* pieces[] = {&king, &queen, &rook};

Ideally, I'd like having

Piece* pieces[] = {
    &King{square},
    &Queen{square},
    &Rook{square}
};

But I can't use addresses of temporary objects.

Is there a neat way to write the constructors directly inside the initializer list?

1 Answers

consider using new operator that returns a pointer to the heap allocated object, so your object is no-longer a temporary value.

Piece* pieces[] = {
    new King{square},
    new Queen{square},
    new Rook{square}
};

but you have to call delete on every item in the array before the array is deleted so you won't have a memory leak.

instead i'd recommend using shared pointers (or unique pointers), and make your array an array of shared pointers, and use make shared instead of new, so you don't have to worry about memory leaks.

std::shared_ptr<Piece> pieces[] = {
    std::make_shared<King>(square),
    std::make_shared<Queen>(square),
    std::make_shared<Rook>(square)
};
Related