Because the expression r = bb
is exactly equivalent to aa = bb
. The assignment operator merely copies the parts of bb
known to the AA
class into the aa
object.
In other words, after the assignment, r
still points to aa
, which is an instance of AA
. It does not point to a BB
instance in any sense.
A reference can never change which object it refers to, so the expected behavior cannot be achieved with references. To get the polymorphism you're looking for, you muse use pointers:
AA* p = &aa;
p->print();
p = &bb;
p->print();