Re: Question regarding cast
somenath <somenathpal@gmail.com> wrote:
But why it is different? What is achieved by having different address
of same object? Could you please explain how compiler does it?
In functions that take a pointer or reference of the base class type,
it is assumed that all the member variables are at certain offsets from
said pointer. This is true for the member functions of said class as well
(in which the pointer to the object is 'this'.)
So if you have something like "this->a = 5;" (or "a = 5;" for short),
what happens internally is that the code takes the pointer, adds a
certain fixed offset value to it, and assigns 5 to that memory location.
(This is very efficient because most CPUs support "indexing" of pointers
directly in machine code, without any actual additions being made.)
In simple inheritance this is all fine and dandy because a pointer to
the derived class is the same as the pointer to the base class. (The
layout in simple inheritance is that the contents of the base class
are at the beginning of the memory block and the contents of the derived
class after that.)
In multiple inheritance, however, things change. Likewise in the most
typical implementations of dynamic binding (ie. virtual functions).
If, for example, the base class has no virtual functions but the derived
class does, the class layout of the derived class will typically be like:
vtable pointer
contents of A
contents of B
If you are making a class that's multiple-inherited eg. from X and from A,
the layout will typically be like:
contents of X
contents of A
Now, a function taking a pointer or reference to an object of type A
(which, as said, includes A's own member functions) are still the same
as before: They assume that A's contents are at certain fixed offsets
from the pointer. Therefore if you suddenly gave them an unmodified
pointer to the derived object, the program would break, because now
they would be reading from and writing to the completely wrong locations.
For this to not break, what happens is that when a pointer or reference
of the derived type is cast to the base type (implicitly or explicitly),
it is adjusted to point to the base class part inside the object. This
way all the functions will keep working as they should.
--- news://freenews.netfront.net/ - complaints: news@netfront.net ---