Re: Question regarding cast
Am 19.06.2013 10:58, schrieb somenath:
On Wednesday, June 19, 2013 11:23:07 AM UTC+5:30, Ike Naar wrote:
/* begin code */
#include <iostream>
class Base1 { char i; };
class Base2 { char j; };
class Derived : public Base1, public Base2 {};
int main()
{
Derived d;
Base1 *b1 = &d;
Base2 *b2 = &d;
std::cout << "&d=" << &d << " b1=" << b1 << " b2=" << b2 << "\n";
return 0;
}
/* end code */
/* begin output /*
&d=0x7f7fffffdb40 b1=0x7f7fffffdb40 b2=0x7f7fffffdb41
/* end output */
But I am not getting why it needs to be different?
Think about the memory layout. In this case, we obviously have
something like this:
Derived object
|
V
,-- --.
0x7f7fffffdb40 | i | <-- Base1 object
| --?
| --.
0x7f7fffffdb41 | j | <-- Base2 object
`-- --'
where the address you see is the object's starting address.
What you should keep in mind is the following: If you have a Base1 or
Base2 pointer and you know already that it points to a subobject of a
Derived object, you need a static_cast to get to a Derived pointer
because a static cast will include a pointer adjustment if necessary:
Derived d;
Base1* p = &d;
Base2* q = &d;
Derived* x = static_cast<Derived*>(p);
Derived* y = static_cast<Derived*>(q);
assert(&d == x);
assert(&d == y);
(A reinterpret_cast would not work here)
Of course, if your classes are polymorphic, then you could also use a
dynamic_cast for this.
Cheers!
SG