Does polymorphism work in C ++ without pointers / references?
Yes and no.
Dynamic polymorphism works in C ++ when the static type of a pointer or reference may differ from the dynamic type of the object to which it refers, and the behavior is selected based on the dynamic type. This requires pointers or references, since the object itself has only one type.
Static polymorphism, using templates, works great with objects, but solves a different class of problems. In your example, dynamic polymorphism is required to select behavior based on the runtime type of objects.
which function will be called?
The vector contains objects of type A , so A::do_it() will be called. The object does not know that it was created by slicing an object of type B
In principle, is it possible to use polymorphism without pointers if there is no cutting?
Slicing is always present when you create objects of a base class from objects of a derived class. This is the definition of cutting.
Mike seymour
source share