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?

  • Did you see the remark in point expr.add / 6 ? - wololo
  • It is a wololo
  • @wololo, but ibid "where T and the array element type are not similar" - Qwertiy
  • one
    I would first recommend removing the use of a heap from the code, or at least delete , so as not to impose one UB on another. - αλεχολυτ
  • 2
    So their system generates by default and they are not virtual . - αλεχολυτ

0