Polymorphism - "pointers" or "references"?
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++:
=================================================
And when I was using polymorphism "feature" in Java, I wrote this:
Code:
Shape shape = new Circle();
which in c++ code would look like this:
Code:
Shape* shape = new Circle;
That's fine, all is great and I understand it.
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:
Code:
Circle circle;
Shape& shape = circle;
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).
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.
References: "no object slicing"?
Quote:
Originally Posted by
Elysia
Slicing only occurs if you try to store (or pass) a copy of a polymorphic type.
If you store or pass the objects by reference or by pointer, no slicing will occur.
So you can safely pass objects via reference without worry of slicing.
Wow,
so that is great, I thought that only in the case of "pointers" (as function arguments) the slicing doesn't occur.
Thus, if I understand it well, when using the reference technique...
Code:
class Shape {};
class Circle : public Shape {};
// Function argument as reference...
void polymorphicFunction(const Shape& shape)
{
/* Some code */
}
int main()
{
Circle circle;
Shape& someShape = circle;
// Pass the circle "as a shape" to the function
polymorphicFunction(circle);
}
...no object slicing will occur?
Thanks.