There is a class A from which class B is inherited. However, class B does not contain any fields. If I create an array of B elements, but use it as an array of A elements, will it be correct?
The standard states that this is allowed only with similar types:
It is a type of pointer that has been added. The expressions P and J and J (where J has the value of j) + j] if 0 ≤ i + j ≤ n; otherwise, the behavior is undefined. Likewise, the expression of the (possibly-hypothetical) element x [i - j] if 0 ≤ i - j ≤ n; otherwise, the behavior is undefined.
The similarity of types is described nearby , but I cannot understand whether types in my case are similar. Which types are considered similar?
Here is a sample code: https://ideone.com/ncRepZ https://ideone.com/nMvJ0r
Does it contain undefined behavior?
#include <iostream> using namespace std; struct A { int x; A(int x) : x(x) {} virtual ~A() {} }; struct B : A { B() : A(7) {} }; int main() { A *a = new B[4]; for (size_t q=0; q<4; ++q) cout << q << ": " << a[q].x << endl; delete [] a; return 0; } In case it is still not allowed, is it enough to add a check for equality of the sizes of these two types https://ideone.com/iSkJk0
static_assert(sizeof (A) == sizeof (B), "B must have same size as A"); to ensure that if a program is compiled, does it contain UB?
delete, so as not to impose one UB on another. - αλεχολυτvirtual. - αλεχολυτ