How to Prevent Unintentional Object Slicing When Using std::vector in C++?
I'm having a hard time understanding Quick question that's been bugging me - I'm currently working on a C++ project using C++17 and I ran into an issue with object slicing while storing derived class objects in a `std::vector`. I have a base class `Shape` and a derived class `Circle`. Here's a simplified version of my code: ```cpp class Shape { public: virtual void draw() const { std::cout << "Drawing Shape" << std::endl; } virtual ~Shape() = default; }; class Circle : public Shape { public: void draw() const override { std::cout << "Drawing Circle" << std::endl; } }; std::vector<Shape> shapes; shapes.emplace_back(Circle()); // This line causes slicing ``` When I try to add a `Circle` object to the `shapes` vector, I'm getting unexpected behavior. Specifically, when I call `shapes[0].draw()`, it outputs "Drawing Shape" instead of "Drawing Circle". This suggests that the `Circle` object is being sliced and only the `Shape` part is being stored. I attempted to resolve this by changing the vector to store smart pointers instead: ```cpp std::vector<std::unique_ptr<Shape>> shapes; shapes.push_back(std::make_unique<Circle>()); ``` While this approach works and correctly calls `Circle::draw()`, Iām concerned about the overhead of using smart pointers for a simple case like this. Is there a more efficient way to prevent object slicing while still using a vector without involving pointers? What are the best practices in handling this scenario, especially regarding performance and memory management? Any insights would be greatly appreciated. Thanks in advance! Thanks, I really appreciate it!