views:

122

answers:

3

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

DrawEngine:render(Shape *shape)
{
    shape->draw();
    shape->visible(true);
}

And passing in pointer to various Shape derived classes. Does it work the same with references

DrawEngine:render(Shape &shape)
{
     shape.draw();
     shape.visible(true);
}

is it even valid to do

engine.render(myTriangle); // myTriangle instance of class derived from Shape

If this works are there any differences between the two cases? I tried to find info in Stroustrup but found nothing.

I reopened this cos I wanted to explore just a tad more.

so at least one difference is dynamic_cast. For me polymorphism includes the use of dynamic_cast

can I go

Rhomboid & r = dynamic_cast<Rhomboid &>(shape);

what happens if the cast fails. Is this any different?

Rhomboid * r = dynamic_cast<Rhomboid*>(&shape);
+5  A: 

With regard to polymorphism, references work just like pointers.

Alex Emelianov
an answer doesn't get much simpler than that - thx
pm100
@Alex @pm100: Directly, sure, but there are different facets. For example, `dynamic_cast` will throw an exception rather than return null on a bad cast.
GMan
@GMan: I think of the `dynamic_cast` example as of basic difference between pointers and references: pointers can legally be NULL, while references cannot. The heart of the question, as I read it, is whether references behave the same with regard to virtual tables. Hence the brief answer.
Alex Emelianov
The way I see it, references seems to be little more than syntactic sugar on top of pointers.
Etienne de Martel
@Etienne, that is certainly true for every compiler I have encountered. But I don't get out much.
Mark Ransom
A: 

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.

vinayvasyani
A: 

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.,

Alf P. Steinbach