Re: How dynamic_cast works internally?
On Oct 23, 8:55 am, Bo Yang <struggl...@gmail.com> wrote:
Erik Wikstr=F6m
[...]
RTTI is part of the C++ standard, do not confuse it with reflection
though. One way to accomplish this (though I do not think that is how it
is done) would be to add a second pointer (in addition to the vtable)
which points to a type object looking something like this:
class Type
{
char name[];
Type* super[];
Type* derived[];
};
That way typeid could (conceptually) be implemented something like this:
template<typename T>
type_info typeid(T t)
{
return type_info(t->typePtr->name)
}
And using some simple tree walking algorithms you can find out if a type
is in the same type-hierarchy as another.
The "extra pointer" is usually in the vtbl, not in the object
itself. Types with a virtual function will have a vptr to the
vtbl anyway, so RTTI is essentially free for them if they don't
use it. (It increases the size of the static data associated
with the type, but this is typically a negligeable part of the
total program size.)
In the simplest implementation, all of the necessary information
will be wrapped up in the type_info object, there will be
exactly one type_info object per type, and its address serves as
the identity. From what I understand, this isn't possible for
some implementations of dynamically loaded objects, where you
end up with a type_info object per dynamically loaded object; in
such cases, typically, the implementation will first tree walk
using the addresses for identity, and if this fails, will repeat
using string comparisons on the names.
So, C++ type conversion will be time-consuming and
space-consuming, right?
Dynamic_cast will take a bit more time than a static_cast. On
the other hand, it leads to a lot less core dumps.
Space consumation is generally very small, not nearly as much as
what is required for a good implementation of exceptions, for
example. Probably less that 100 bytes per polymorphic type.
And maybe that is why C++ program is much more big than C's?
I doubt it. In my experience, the main reason why C++ programs
are bigger is because they do much more. With a good class
library, it's easy to add functionality which would cost too
much to add in C.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34