Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Inserting different types of objects into one queue

Hi,
I wish to place objects of class B and class C into one queue. The queue, say class Queue, is a class template. Further, B and C are derived from class A. Can I say something like:

Queue<A> qobject;
B bob;
C cat;
qobject.insert(bob);
qobject.insert(cat);

or do I have to cast objects of B and C to type A before insertion. If so how do I cast objects from one type to another at run time.
Also, if the above is possible how do I, when removing objects from the queue, know which type of object I am removing.

I would be grateful for all help
[710 byte] By [ray] at [2007-11-11 7:49:09]
# 1 Re: Inserting different types of objects into one queue
I would make a union or a class with pointers to all the classes and make a Q of that.
jonnin at 2007-11-11 21:01:54 >
# 2 Re: Inserting different types of objects into one queue
couldn't you "cast" them at time of creation of the objects?

A* bob = new Bob;
A* cat = new Cat;

now the object pointer is of the supertype A but are constructed as objects of the child classes .. and they can be added to the queue ...
nspils at 2007-11-11 21:02:54 >
# 3 Re: Inserting different types of objects into one queue
Actually, what you're looking for is a heterogeneous conatiner. I discussed it recently:
http://www.dev-archive.com/cplus/10MinuteSolution/29757
The pointer cast option is applicable only if you a hierarchy of classes, i.e., B is derived from C
Danny at 2007-11-11 21:03:54 >