Sign in to follow this  

union of pointers

This topic is 3738 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Is there anything wrong with having a union of pointers to different types? for example if I have a class Light, PolyObject, Particle, etc. then I do something like this: class Renderable { ... enum { LIGHT, OBJ, PARTICLE } mType; union { Light* light; PolyObject* obj; Particle* particle; } mPointer; } I tried googling to see if there were any pitfalls to doing this or if this is common practice, but I could not find anything substantial.

Share this post


Link to post
Share on other sites
Theres nothing *wrong* with it, but unions are generally avoided because they can be confusing.
That said, I've done what you're doing before (combining a union with an enumerated type).


However, if you later want to replace those pointers with some kind of smart-pointer, then the union *will* cause you trouble.

Share this post


Link to post
Share on other sites
You have several better options:
  • Proper design, separating lights, objects and particles into distinct containers of these objects.
  • Proper design, providing lights, objects and particles with a common interface so that you don't need to know their type to manipulate them.
  • Proper code, using boost::variant for improved type safety.
  • Proper code, giving your lights, objects and particles a shared based class and using a visitor and virtual function system to do dynamic dispatch.

Share this post


Link to post
Share on other sites
Would it work to use Renderable as a base class for Light, PolyObject, and Particle? That way you could have a function something like GetType that would return LIGHT, OBJ, or PARTICLE. Then you could use virtual functions to actually render the object.

Share this post


Link to post
Share on other sites
Quote:
Original post by F-Kop
Would it work to use Renderable as a base class for Light, PolyObject, and Particle? That way you could have a function something like GetType that would return LIGHT, OBJ, or PARTICLE. Then you could use virtual functions to actually render the object.

If you already have virtual functions that deal with the object, why would you need to know the type of that object on a container that would care only for the interface?

Share this post


Link to post
Share on other sites

This topic is 3738 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this