I've this piece of code:
#include <iostream>
class A
{
public:
A() : m_i(0) { }
protected:
int m_i;
};
class B
{
public:
B() : m_d(0.0) { }
protected:
double m_d;
};
class C : public A, public B
{
public:
C() : m_c('a') { }
private:
char m_c;
};
int main()
{
C d;
A *b1 = &d;
B *b2 = &d;
std::cout << (long)b1 << std::endl <<(long)b2<< std::endl;
}
when compiled and run it produces the following output:
140734705182320
140734705182328
It is not completely clear why different pointers to the same address (&d) have different values.
thanks in advance.
The memory layout of a C
object will be something like:
A base_object_1;
B base_object_2;
char m_c;
The two base objects have different addresses; A
will (typically) have the same address as the full object, but B
will (typically) not. Certainly they can't have the same address as each other, unless at least one is empty.
So converting a pointer to the full object into a pointer to one of the base objects must change the pointer value in order to point to the correct address.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With