1
class A{
    int a;
};
class B : public  A{
    int b;
};
class C : public  B{
    int c;
};

int _tmain(int argc, _TCHAR* argv[]){
    C c;
    C* pc = &c;
    B* pb = &c;
    A* pa = &c;
    printf("%d\n", pc); //4344
    printf("%d\n", pb); //4344
    printf("%d\n", pa); //4344
    return 0;
}

All(pa,pb,pc) point to the same address "4344" , aren't they suppossed to be different?

-------------UPDATE-------------
If they are suppossed to be the same ,then when I change the code to this , pa would point to different address :

class A{
    int a;
};
class B {
    int b;
};
class C : public  B , public A{
    int c;
};

int _tmain(int argc, _TCHAR* argv[]){
    C c;
    C* pc = &c;
    B* pb = &c;
    A* pa = &c;
    printf("%p\n", pc); //4344
    printf("%p\n", pb); //4344
    printf("%p\n", pa); //4348
    return 0;
}

How to explain these?

user3720957
  • 173
  • 1
  • 6
  • 2
    Use `%p` to print a pointer – M.M Aug 30 '15 at 05:23
  • using the wrong format for printf invokes undefined behavior [Correct format specifier to print pointer (address)?](http://stackoverflow.com/q/9053658/995714) – phuclv Aug 30 '15 at 05:52
  • 2
    undefined behavior my ass ;-) – Peter - Reinstate Monica Aug 30 '15 at 05:54
  • For an explanation see e.g. http://www.cs.bgu.ac.il/~spl121/Inheritance. Nicely explained. – Peter - Reinstate Monica Aug 30 '15 at 05:57
  • size of pointers and int might not be the same, esp. in 64-bit systems, hence printing with `%d` may not result in the correct value. There's nothing unreadable in the hex address, as they are also digits just like decimal – phuclv Aug 30 '15 at 05:57
  • While we're on this topic, using `%p` on a pointer that's not a `void *` also causes undefined behaviour. But we usually ignore that for practical reasons. – M.M Aug 30 '15 at 06:07

2 Answers2

1

No they are pointing to the same object i.e. c. Thus you will have same address. And you should not print addresses as %d but %p. https://10hash.com/c/stdio/#fprintf or even better http://pubs.opengroup.org/onlinepubs/009695399/functions/fprintf.html

Shiv
  • 1,912
  • 1
  • 15
  • 21
0

You are assigning all pointers to the same address:

C* pc = &c;
B* pb = &c;
A* pa = &c;

I'd say that makes it very clear that they should be the same.

Saeb Amini
  • 23,054
  • 9
  • 78
  • 76
  • 2
    "You are assigning all pointers to the same address": Not necessarily. The assignment to pb and pa involves a type conversion which principally could change the pointer's value. I am not sure whether the language guarantees that the numerical value is identical for conversion to base class ptrs in single inheritance (although of course "appending" extensions in a class layout is an obvious implementation, and probably necessary for preserving inherited member offsets). What happens with multiple inheritance? – Peter - Reinstate Monica Aug 30 '15 at 05:42