[Nottingham] C++ Programming

Jim Driscoll j at rjimlad.org
Thu Oct 16 07:02:25 BST 2003


On Wednesday, October 15, 2003, at 09:35 PM, David Bean wrote:

> On Wed, 2003-10-15 at 19:08, Martin wrote:
>> Try newsnet. There's some very active C and C++ groups on there.
>
> Do you have a URL?
>

I think he's alluding to newsgroups (your ISP should have an NNTP 
server). I expect there's a comp.lang.c++.newbies newsgroup or 
something like it.

>> Then again, you could always try the folk here. You might get some
>> surprisingly good answers...
>
> OK then, here goes...
>
> I'm using SDL. I have a Keyboard class which intercepts all the 
> keyboard
> events. I want to have various classes call a method of the keyboard
> class and register an id. When a key is pressed it looks up the
> event.key.keysym.sym in a table and see if it corresponds to an id. If
> it does then I want it to call a method in the class instance that
> registered the id (with the sym, in case it registers more than one
> key).
>

You don't want function pointers then. Just normal - object - pointers 
(typed as a superclass with that function "virtual").

>   bool registerKey(Uint16 sym, bool(*func)(Uint16 sym));
> I thought something like this could work, but it only works on static
> functions. I want class instances to register individual keys, so if I
> have a button class, each instance of the button class can ask for a
> different id/be mapped to a different key.
>
> Something like:
>
>   Button::Button(Keyboard k, Uint16 id) {
>     k.registerKey(id, &keyPressed(Uint16))
> ...
>   }
>   bool Button::keyPressed(Uint16 sym) {
> ...
>   }
>
>   Menu::Menu(Keyboard k, Uint16 id) {
>     k.registerKey(id, &keyPressed(Uint16))
> ...
>   }
>   bool Menu::keyPressed(Uint16 sym) {
> ...
>   }
>
> Does anyone have any code, or better ways of doing this? The point is 
> to
> make the keyboard mapping changeable at runtime without a big switch
> statement.
>

If the objects aren't actually used for anything (besides containing 
the methods mentioned), you should probably just stick with function 
pointers. Otherwise, you should have something like:

class SuperKeyClass {
	virtual bool keyPressed(UInt16 Sym);
...
};

...and derive your classes from that. Your books will explain 
inheritance; it's one of the key parts of C++.

Jim




More information about the Nottingham mailing list