values of base-class pointers when assigned the address of derived-class objects

Hello everyone,

I have the following piece of code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#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 << &d << std::endl << b1 << std::endl << b2 << std::endl;

    return 0;
}


I was expecting to obtain the exact same address of memory 3 times, but this is not the case. The output is the following:


0x7fff5fbff960
0x7fff5fbff960
0x7fff5fbff968


Any idea why? Thanks in advance for the explanation.
Last edited on
i'm not sure how you even go that to happen. class A, class B, and class C are totally different, and the compiler should have flagged that the pointers are you are trying to assign are of different base classes.
Regarding pogrady post:

i'm not sure how you even go that to happen. class A, class B, and class C are totally different, and the compiler should have flagged that the pointers are you are trying to assign are of different base classes.


I have created 2 pointers of 2 different base classes and assigned to each one of them the address of an instance of the class that is derived from both of these base classes. No problem with that. Just try to compile it.

If you know the answer to the question post it, if not, then don't post anything, thanks.
I don't know for sure, but if you consider class as struct:

class A's objects will have size of 4 bytes (only an integer)
B's - 8 bytes (only a double)
C's: derive from A and B, so it will have at least 4+8 or 8+4 = 12+ bytes

depends on your declaration the structure of a C's object will be

1
2
3
4
5
 0  1  2  3   4  5  6  7  8  9  10 11 
[A][ ][ ][ ] [B][ ][ ][ ][ ][ ][ ][ ] ...  (case 1)
or
 0  1  2  3  4  5  6  7   8  9  10 11 
[B][ ][ ][ ][ ][ ][ ][ ] [A][ ][ ][ ] ...  (case 2)


so a class A pointer point at C will point at either 0 (case 1) or 8 (case 2)
and class B pointer point at C will point at either 4(case 1) or 0 (case 2)

and for calling class A methods from *b1, the compiler will use 4 bytes of d after b1, calling class B methods from *b2, the compiler will use 8 bytes of d after b2, calling an override method of class C will use all bytes of d.

I guess your case should be case 1, because you declare public A, public B, so A first B second, 4+8, pointer b1 and b2 should be different by 4, not 8 :/

My output:
0xbf60e0ac
0xbf60e0ac
0xbf60e0b0

b1 and b2 is different by 4
Last edited on
Topic archived. No new replies allowed.