Calling base function through wrong pointer

Viewed 115

Putting aside all the good practices against writing code like below, just from the language lawyer perspective, is the following snippet legal?

struct Base {
  int f() { return 42; }
};
struct D1 : Base {};
struct D2 : Base {};

int main() {
  D2 d2;
  D1* ouch = reinterpret_cast<D1*>(&D2);
  return ouch->f();
}

It seems to me that [class.mfct.non.static] is the most relevant clause and that it suggests it is ok, as we are calling a non-static member function for an object of a derived class.

Should it happen that the non-virtual case is indeed legal, does anything change if f or the inheritance is virtual?

1 Answers

CWG 2535 underlines that, unlike for unions (where common initial sequences of standard layout types can be reused), accessing class members through a pointer of distinct class type is undefined.

For an instance of practical relevance: if you used the created pointer to modify a member of d2, that could be rearranged with other accesses to that member during optimization, as a result of alias analysis.

Related