Re: Advanced Type Casting guide?
Roberto <robitabu@yahoo.com> wrote:
Anybody can suggest me some advanced guide on C++ type casting?
I'm mostly interested in what happens in memory whenever type
up/down-casting is performed.
Perhaps if you would ask more specific questions, we could answer
them right here.
If you are talking about how a pointer to an object changes when
it's casted (up or down) in an inheritance hierarchy (with either
dynamic binding or not) is a relatively interesting, albeit rather
low-level, subject.
In the vast majority of object-oriented languages out there
references/pointers to objects never change because these languages
tend to have very simple inheritance rules (namely, all classes are
always dynamically bound, and multiple inheritance is not supported).
C++ is much more complicated in this aspect because its inheritance
rules are much more varied. For instance, it makes a difference whether
a class has dynamic type info (iow. whether it or one of its base classes
has at least one virtual function) or not, and multiple inheritance makes
it even more complicated (not to talk about when you start using virtual
inheritance).
Many C++ programmers don't actually know that dynamic_cast can in some
cases actually be a linear-time operation (with respect to the amount
of classes in the inheritance hierarchy). For example, the fact that this
works surprises many even experienced C++ programmers:
class A // no relation to B
{
public:
virtual ~A();
};
class B // no relation to A
{
public:
virtual ~B();
};
void foo(A* objectA)
{
B* objectB = dynamic_cast<B*>(objectA);
if(objectB) ...
}
Does the above compile? Answer: Yes.
Does it work properly in a situation like this?
class C: public A, public B
{
};
void bar()
{
C objectC;
foo(&objectC);
}
Answer: Surprisingly, yes. The dynamic_cast will succeed in this
case even though foo() has no knowledge whatsoever about class C.
Regardless, it will be able to cast the pointer of type A to a pointer
of type B in a multiple-inheritance situation like this.
Naturally the cast is relatively complicated inside. (Consider that
the V-shaped multiple inheritance hierarcy could be really large and
complex.)