Are references and pointers equal with regards to polymorphism?

前端 未结 3 722
南笙
南笙 2020-12-08 10:05

I always think of having to use pointers for polymorphism. Using the canonical example:

DrawEngine::render(Shape *shape)
{
    shape->draw();
    shape-&g         


        
3条回答
  •  没有蜡笔的小新
    2020-12-08 10:27

    Regarding dynamic_cast, a failed cast produces a nullpointer with pointers, and results in a throw of a bad_cast (IIRC) exception with references.

    One reason is that there's no such thing as a valid null-reference.

    And possibly another reason (but it could just be an unintentionally useful emergent feature) is that sometimes one needs the exception and sometimes one needs the easy-to-check nullpointer, and no matter whether you have a reference or pointer at hand it takes at most a dereferencing or address operator to obtain the behavior you want.

    Cheers & hth.,

提交回复
热议问题