Re: C++ RTTI and derived classes
This is a MIME GnuPG-signed message. If you see this text, it means that
your E-mail or Usenet software does not support MIME signed messages.
The Internet standard for MIME PGP messages, RFC 2015, was published in 1996.
To open this message correctly you will need to install E-mail or Usenet
software that supports modern Internet standards.
--=_mimegpg-commodore.email-scan.com-2853-1260848052-0001
Content-Type: text/plain; format=flowed; charset="US-ASCII"
Content-Disposition: inline
Content-Transfer-Encoding: 7bit
Shaun writes:
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:
Your base class needs at least one virtual function in it, in order to get
RTTI working the way you want. Since, in most cases, virtual destructors are
used, that takes care of that.
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.
Since both of your objects are Cmd *, that's the method you end up calling.
When resolving overloaded functions, the binding occurs at compile time, not
runtime.
There are a number of ways to do this. I prefer to define a virtual
Cmd::handleCommand(Target *t) that's defined in Cmd, CmdA, and CmdB, in all
three cases invoking t->handleCommand(this). You would invoke
Cmd->handleCommand(t), which binds at runtime, through the virtual function,
to the appropriate instance of the subclassed method, which then invokes the
appropriate overloaded method in Target.
--=_mimegpg-commodore.email-scan.com-2853-1260848052-0001
Content-Type: application/pgp-signature
Content-Transfer-Encoding: 7bit
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.10 (GNU/Linux)
iEYEABECAAYFAksnA7QACgkQx9p3GYHlUOJkFgCeKafMM5sUVA4EAYgz2zMbcB84
saUAn1Wn/Or95SN9ffrg43C/KSRbrecv
=enQS
-----END PGP SIGNATURE-----
--=_mimegpg-commodore.email-scan.com-2853-1260848052-0001--