What will be the printed?

#include <iostream>

struct A {
  virtual ~A() {}

struct B {
  virtual ~B() {}

struct C: A, B {};

using namespace std;

int main()
    C Object;
    A *a(&Object);
    B *b(&Object);
    cout << boolalpha << ((void*)a==(void*)b) << ", "
    << (a==&Object) << ", " << (b==&Object) << ".\n";
    return 0;
In C++ the object can have more than one valid address. A comparison​ of pointers is not a question of addresses. Comparison of pointers is a question about the identity of objects.
In the context of this example, we cannot talk about identity A and B, because there is no inheritance relationship between them, and in any case, the objects of these types will be physically located in different memory locations.
However, we can talk about the identity of the objects A - C and B - C, because each pair is bound by an inheritance relationship.
Recall also that in C++ the standard does not regulate the mutual arrangement of parent objects inside an object of a child class. It can be anything. For example, the first of the parent class objects does not necessarily lie at the beginning of the child object, there may be gaps between the parent class objects and it is not known where the compiler will put the object of the virtual base class.
Thus, only the compiler knows the subobject offsets inside the object.
Now let's look at the expression:
a == &Object
The compiler will insert the following code (roughly) into this code defining the result of the expression:
a ? (a + offset == &Object) : (&Object == 0) 
where offset is the subobject shift inside the object
In other words: a and &Object are equal if and only if (they are both zero) or (a + the known offset coincides with &Object).
Keep in mind that this substitution occurs only when the compiler has the type information required for comparison. Once we get the pointers to the untypified void *, the compiler has no choice but to compare unsigned integers.
See also:
Stephen Dewherst "C++ Sacred Knowledge" Themes 11 and 28.
Stephen Dewhust "C++ Common Knowledge" Item 11 and 28.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Sign Up Now
or Subscribe for future quizzes