Linked list and variable datatypes

Hey there,

I would like to know wether it's possible to have the nodes in a linked list contain data from just a single type, but be able to obtain any of a couple of types. I know this explanation is a bit strange, so I'll give an example:

Imagine we're building a particle-system
We have a Particle class, a Sand class and a Water class. The Sand and Water classes inherit from the Particle class.

We also have a (doubly) linked list system (which consists of a DoubleLL class and a DoubleLLNode struct. This last-mentioned struct is the type of our nodes in the linked list, ofcourse.

Now imagine that we want to use the linked-list's nodes to hold a pointer to a particle. Effectively giving us a linked list of particles. Would it then be possible to make each node contain ONE pointer (besides the ones pointing to previous or next nodes) which points to either a Sand-class instance or a Water-class instance?I mean by this that the node should not be able to contain pointers to instances of both types, just a single pointer to a single type. Because of the fact that there must only be a single pointer, the type of this pointer should be variable as far as I know.

I heard from someone that I could use a union to do this, as it would allow me to declare two pointers (one for Sand and one for Water) and the union would allow me to set either of these pointers, making the other one unavailable automatically.

Something like this:

1
2
3
4
5
union
{
   Sand* p;
   Water* p;
};


Which would translate to having just one variable pointer p pointing to either an instance of the Sand class or an instance of the Water class.

Would this be possible? I've tried it, but it fails when trying to compile already.
The Sand and Water classes inherit from the Particle class.

Use polymorphism. std::list < Particle * >. You don't know what type your particle is, but that is not important
Last edited on
Thanks a bunch ne5555! It's working exactly as I wanted now :)
Topic archived. No new replies allowed.