Reputation: 173
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?
Upvotes: 1
Views: 120
Reputation: 24439
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.
Upvotes: 0
Reputation: 1952
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
Upvotes: 1