Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: pointer comparison of base vs derived of the same object

example:

class A{
    int x;
};
class B{};
class C : public A, public B {};

C c;
A* a = &c;
B* b = &c;

when I check the value of &c and b, they are different because b is after a in memory, but yet when I evaluate &c==b, they are the same, why is the case?

like image 248
gdlamp Avatar asked Oct 15 '12 06:10

gdlamp


1 Answers

In the expression &c == b both operands have to be coerced to the same type. In this case &c (a C*) can be converted to B* as B is an accessible base class of C. This is exactly the same conversion as happens in B* b = &c so the resulting values are the same and the comparison returns true.

like image 51
CB Bailey Avatar answered Oct 05 '22 04:10

CB Bailey