Trying to figure out something (in Hell, actually) I came up with the following code. Why is this legal?
class Superclass {
public:
virtual void Announce() {
printf("I am the superclass\n");
}
};
class Subclass : public Superclass {
public:
void Announce() {
printf("I am the subclass\n");
}
};
int main() {
Superclass osuper;
Subclass osub;
Superclass* p = &osub;
*p = osuper;
osub.Announce();
return 0;
}
In main()I create an instance Subclass, then physically overwrite it with an instance Superclass. Then I successfully call the method Subclasson the rewritten (and so damaged) object.
I canβt directly assign osub = osuper, because it doesnβt make sense, but by going through the pointer I seem to get around this. The above code compiles without warning, but by the time I call osub.Announce(), the memory inside osubno longer contains a valid object Subclass.
It may not be type safe (or even, as is usually safe), but the compiler looks completely happy. Why?