In Item 27 of \"Effective C++\" (3rd Edition, Page 118), Scott Meyers said:
class Base { ... };
class Derived: public Base { ... };
Derived d;
Base *pb = &am
An object has exactly one address; that's where it's located in memory. When you create a pointer to a base subobject you get the address of that subobject, and that doesn't have to be the same as the address of the object that contains it. A simpler example:
struct S {
int i;
int j;
};
S s;
The address of s
will be different from the address of s.j
.
Similarly, the address of a base subobject does not have to be the same as the address of the derived object. With single inheritance is usually is, but when multiple inheritance comes into play, and ignoring empty base classes, at most one of the base subobjects can have the same address as the derived object. So when you convert a pointer to the derived object into a pointer to one of its bases you don't necessarily get the same value as the address of the derived object.
Just try it:
class B1
{
int i;
};
class B2
{
int i;
};
class D : public B1, public B2
{
int i;
};
int
main()
{
D aD;
std::cout << &aD << std::endl;
std::cout << static_cast<B1*>( &aD ) << std::endl;
std::cout << static_cast<B2*>( &aD ) << std::endl;
return 0;
}
There's no possible way for the B1
sub-object to have the same
address as the B2
sub-object.