Polymorphism only works on pointers and references. If you assign a B
to an A
, it becomes an A
and you lose all B
-specific information, including method overrides. This is called "slicing"; the B
parts are "sliced" off the object when it is assigned to an object of a parent class.
On the other hand, if you assign a B*
to an A*
, it looks like an A*
, but is still really pointing to a B
, and so the B
-specific information remains, and B
's virtual overrides will be used.
Try:
int main(){
A* ab = new B();
ab->print();
delete ab;
while(true){}
}
The same also applies to assigning a B
to an A&
(reference-to-A
), e.g.
int main(){
B b;
A& ab = b;
ab.print();
while(true){}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…