Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Let\'s say we\'re designing a video game. We have some sprites on the map and we

ID: 654300 • Letter: L

Question

Let's say we're designing a video game. We have some sprites on the map and we want to call some method of the particular sprite at some particular position.

We are using one broadly-known C++ framework. It has an GraphicsItem class, and ALL our sprites are derived from it. Now, framework has a method to get a pointer of the GraphicsItem at any position on the map.

We've got two options now:

Cast from GraphicsItem* to our Sprite* and call Sprite's method. (We know for sure that all the graphics items on the map are instances of Sprite)

Make some crazy things like Store pointers to Sprite in some container, iterate through them, compare address vales and get straight Sprite* without casting.

The question is: what is the best practice in this case? I was always told to avoid typecasting because it means you've got design issues. But how can I change design to avoid typecasting here? And extra iteration over a container with a comparison is just... crazy...

Explanation / Answer

If you know that everything in the scene is an instance of Sprite, then there should be no problem with typecasting. You can enable RTTI and use dynamic_cast<Sprite *> to be extra certain.

If there may be other GraphicsItem elements that are not instances of Sprite, then you could keep a set (perhaps QSet<GraphicsItem *>) which holds pointers to instances of Sprite that should appear in the scene. When you get a pointer from the scene, check to make sure it is in the set of sprites. This has the disadvantage of requiring that you maintain the set alongside maintenance of the scene itself.

It certainly would not be necessary to create a mapping container that maps a GraphicsItem * to a Sprite *.