My C++ is a bit rusty. Here’s what I’m attempting to do:
class Cmd { };
class CmdA : public Cmd { };
class CmdB : public Cmd { };
...
Cmd *a = new CmdA ();
Cmd *b = new CmdB ();
First problem:
cout << typeid (a).name ()
cout << typeid (b).name ()
both return Cmd * types. My desired result is CmdA* and CmdB*. Any
way of accomplishing this other than:
if (dynamic_cast <CmdA *> (a)) ...
Second, I would like to do something like this:
class Target {
public:
void handleCommand (Cmd *c) { cout << "generic command..." }
void handleCommand (CmdA *a) { cout << "Cmd A"; }
void handleCommand (CmdB *b) { cout << "Cmd B"; }
};
Target t;
t.handleCommand (a);
t.handleCommand (b);
and get the output “Cmd A” and “Cmd B”. Right now it prints out
“generic command…” twice.
Thanks
Ah but
typeid(a).name()will beCmd*because its defined asCmd*.typeid(*a).name()should returnCmdAhttp://en.wikipedia.org/wiki/Typeid
Also, the base class of whatever you pass to typeid must have virtual functions, otherwise you get back the base class.
MSDN has a more eloquent explanation for that: