Why does the if condition in the following code yield true?
struct A
{
int firstMember;
} a1;
if (&a1 == static_cast<void*>(&a1.firstMember)) std::cout << "equal";
I got a bit confused when reading Stroustrup's FAQ on empty classes, specifically the statement below:
if (p1 == p2) cout << "nice: good optimizer";
There are no references involved in your code. Don't confuse the "address-of" operator (also &
) with references.
Your condition returns true because in this case it happens that the object starts in the same place in memory as its first (and only) field. That's the case i.e. for so-called POD (plain-old-data) objects, but it's not always true.
For example it's likely for the condition to be false if your class contains any virtual functions. Don't depend on it.