I am curious as to how this code snippet compiles:
#include <iostream>
struct A {
virtual unsigned size() = 0;
};
struct B : public A {
unsigned size() {
return 5;
}
};
struct C : public A {
unsigned size() {
return 100;
}
};
void foo(A* a) {
unsigned myArr[a->size()];
std::cout << myArr[10];
}
Shouldn't the compiler complain that a->size() is not a constant expression? It has no idea if it should allocate 5 or 100 spaces for the array. Also, looking at godbolt's disassembly, I cannot find where it actually sizes the array. Should I expect to see that?
Edit: Note that this question is not asking why this feature is not allowed, but rather why it compiles when it is expressly forbidden by ISO C++. Therefore, it is not a duplicate of questions similar to the former question.