#include<stdio.h>
class A { public: int a;};
class B: public A {
int c;
int d;
};
int main() {
A* pA = new B[10];
B* pB = new B[10];
printf("\n%d", pA->a);
pA++;
printf("\n%d", pA->a); // prints junk value
printf("\n\n%d", pB->a);
pB++;
printf("\n%d", pB->a);
return 0;
}
The second printf prints a junk value.
It should figure that it is pointing to an object of type B and increment by the sizof(B).
Why does that not happen?
It can only know that at runtime. Imagine it slightly changed
But that’s not going to happen. C++ puts emphasize in speed, but this would basically make it into a language that ensures safety of operations. There is Java, C# and others that already solve this.
Kernel and device driver developers don’t want a clever language runtime. They just want to have things run fast.
Have a look at Common undefined behavior in C++ question for all the things that will need to get “fixed” along. It won’t be C++ anymore!