Are references and pointers equal with regards to polymorphism?

前端 未结 3 696
南笙
南笙 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.,

    0 讨论(0)
  • 2020-12-08 10:28

    Pointers help in other ways as well. Like passing a string and accepting it as char* parameter in a function.

    Consider the old example of reversing a string in place:

    void reversestring(char* myString)
    {
    int firstPos=0;
    int lastPos=myString.length - 1;
    while (firstPos < lastPos)
    {
      char temp=myString[firstPos];
      myString[firstPos]=myString[lastPos];
      myString[lastPos]=temp;
      firstPos++;
      lastPos--;
    }
    }
    

    Writing code for string manipulation like these using references won't be that simple.

    0 讨论(0)
  • 2020-12-08 10:33

    With regard to polymorphism, references work just like pointers.

    0 讨论(0)
提交回复
热议问题