class A
{
int i;
virtual ~A();
};
class B: public A
{
int j;
};
class C: public B
{
int k;
}
Now, the layout of a C might look like this:
vtable ptr (4 bytes)
A part: int i; (4 bytes)
B part: int j; (4 bytes)
C part: int k;(4 bytes)
Ok, there are certainly implementations that will use that layout.
Now, if the B object is created at the address 10, say, then the
object will run from address 10 though to 24.
?? You don't create a B object on the line below, but a C object.
C* c = new C;
A* a = C;
The value of c above will be 10.
Ok.
The value of a above will also be 10.
Fine.
Ok.
B* b = c;
Now the value of b will be different.
Why? It will still be 10 on normal implementations (I don't know of an
implementation where it will change, and there may well not be one,
although the standard allows it). The B object doesn't care whether
it's a subobject of a C object, a D object or whether it isn't a sub
object at all, but the whole object.
So in single inheritence casting changes the value of the pointer if we are
not casting to top most base class or bottom most derived class.
Why do you think that the value will change in the above case? It
wouldn't make sense for it to change. Try this on your favourite
compilers:
class A
{
public:
int i;
virtual ~A(){}
};
class B: public A
{
public:
int j;
};
class C: public B
{
public:
int k;
};
#include <iostream>
int main()
{
C* c = new C;
B* b = c;
A* a = c;
std::cout << (void*)a << '\n';
std::cout << (void*)b << '\n';
std::cout << (void*)c << '\n';
}
Tom