I am a Java programmer and recently started to learn C ++. I'm embarrassed by something.
I understand that in C ++ you must use either pointers or references to achieve polymorphic behavior. For example, consider the Shape class with the getArea() method implemented. It has several subclasses, each of which differs from getArea () in different ways. Then consider the following function:
void printArea(Shape* shape){ cout << shape->getArea(); }
The function calls the correct getArea() implementation, based on the specific Shape pointed to by the pointer.
This works the same way:
void printArea(Shape& shape){ cout << shape.getArea(); }
However, the following method does not work polymorphically:
void printArea(Shape shape){ cout << shape.getArea(); }
It doesnβt matter what concrete form of Shape is passed into the function, the same getArea() implementation is getArea() : by default in Shape .
I want to understand the technical argument. Why does polymorphism work with pointers and references, but not with ordinary variables? (And I believe that this is true not only for function parameters, but also for something).
Please explain the technical reasons for this behavior to help me understand.
source share