Hi,
I have a little problem about "polymorphism" in c++.
Just for beginning:
=================================================
In "Java" language, there are all the objects (or types) accessed by pointers (we don't write them manually by hand but "they are there").
For example in Java, this code:
means exactly the same as this code in c++:Code:Shape shape;
=================================================Code:Shape* shape;
And when I was using polymorphism "feature" in Java, I wrote this:
which in c++ code would look like this:Code:Shape shape = new Circle();
That's fine, all is great and I understand it.Code:Shape* shape = new Circle;
But there is another thing (what is not in Java): "references".
I have read in various articles that I should prefer references before pointers (where it is possible) because it can improve efficiency and readability of the code (you can correct me if I am wrong).
So I have used to references and now I use them where it is possible.
But the problem is with polymorphism. If I want to use references also with polymorphism, I would write something like this:
But there another problem arises: "object slicing" (I don't want to explain this problem here, let's say that it is just a problem).Code:Circle circle; Shape& shape = circle;
And after this long message, here is my question:
When I use polymorphism feature in c++, is it better to use pointers or references (or plain values) to achieve it (I think, the best thing would probably be to use pointers)?
Thanks in advance.



LinkBack URL
About LinkBacks




