I always think of having to use pointers for polymorphism. Using the canonical example:
DrawEngine::render(Shape *shape)
{
shape->draw();
shape-&g
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.,
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.
With regard to polymorphism, references work just like pointers.