Array of pointers 2 different objects

Started by
4 comments, last by ph0ngwh0ng 20 years, 6 months ago
Hi! I am currently developing a DirectX 9 engine using VC++ .NET. I am extensively using STL as a container library. 1. I have a Input class, which manages input devices etc. Through a public method, objects register to receive input. How can I store different types of objects(or pointers to, doesn''t matter to me) in an array? 2. In the ProcessInput method, I want the Input object to get input from the devices and then send all input semantics to all objects registered for input by the way of a method, implemented in each object, that filters only wanted semantics and further do appliable processing. How do I cycle through my array, described in #1, sending my messages. Thanks for any help! ph0ng^_^wh0ng
ph0ng^_^wh0ng
Advertisement
Why, phongwhong! That''s a rather adroit description of an Event/Listener pattern if I''ve ever seen one.

The key here is to have the objects to be registered inherit from an abstract base class, and have the array (or whatever container you use) be a container of pointers to the abstract base class. That way, you can use virtual function binding to accomplish what you want.

Read up on virtual functions and abstract classes in your C++ book. They''re exactly what you need.

How appropriate. You fight like a cow.
Thank you very much Sneftel!! However, is there another solution?

For example if I store the pointer as a vulgar integer and with it, the size in bytes of my class, wouldn''t there be a workaround somewhere?

ph0ng^_^wh0ng
ph0ng^_^wh0ng
Yikes. Um... yeah, I suppose you could do that. You''d also need to store a member function pointer to the callback function, and do strange and unsafe typecasting things.

But why the heck would you want to? this is exactly what virtual functions are there for.

How appropriate. You fight like a cow.
*evil grin* To trouble your mind!!!!

Nah, just because I am maniac about considering all opportunities before choosing one.

ph0ng^_^wh0ng
ph0ng^_^wh0ng
If you''re looking for alternate methods, it bears mentioning that the C method is to use function pointers, along with callback arguments (which are usually of type void*). The basic idea is that an object (though of course there are no formal objects in C) passes a function (which cannot be a nonstatic member function) into the "register listener" function, usually along with a callback argument; when the event fires, that function is executed, with the callback argument passed back in addition to any event parameters.

How appropriate. You fight like a cow.

This topic is closed to new replies.

Advertisement