Consider the sample code below:
class A
{
public:
A() : n(0) {}
int n;
};
class B
{
public:
B(A* a) : mA(a) { }
B(const A* a) : mConstA(a) { }
union {
A* mA;
const A* mConstA;
};
};
int main()
{
A a;
B b1(&a);
B b2(const_cast<const A*>(&a));
return 0;
}
At construction, b1
would have a mutable pointer to a
, while b2
would have an immutable pointer to a
. In this scenario, b1.mA
equals b2.mConstA
, and b1.mConstA
equals b2.mA
.
Are these equalities always true when you have a union of const
and non-const
object pointers?
Similarly, the code below compiles/runs fine:
int main()
{
const A a;
B b(&a);
b.mA->n = 3; // Blasphemy!!!
return 0;
}
But is it guaranteed for b.mA
to always be equal to b.mConstA
?