Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

c++ - Are references and pointers equal with regards to polymorphism?

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 information in Stroustrup, but I found nothing.

I reopened this because 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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

With regard to polymorphism, references work just like pointers.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...