Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why pointers to the same object have different values? [duplicate]

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.

like image 902
user1131951 Avatar asked Mar 07 '14 17:03

user1131951


1 Answers

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.

like image 171
Mike Seymour Avatar answered Oct 19 '22 04:10

Mike Seymour