advanced patterns When Using std::shared_ptr in a Polymorphic Context with Inheritance in C++20
I've been working on this all day and I'm working with an scenario with `std::shared_ptr` and inheritance in my C++20 project. I have a base class `Shape` and a derived class `Circle`. I'm trying to store different shapes in a vector of `std::shared_ptr<Shape>`, but when I attempt to call a virtual method, it doesn't seem to be behaving as expected. Here's the setup: ```cpp #include <iostream> #include <memory> #include <vector> 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; } }; int main() { std::vector<std::shared_ptr<Shape>> shapes; shapes.push_back(std::make_shared<Shape>()); shapes.push_back(std::make_shared<Circle>()); for (const auto& shape : shapes) { shape->draw(); } return 0; } ``` When I run this code, I expect to see both "Drawing Shape" and "Drawing Circle" printed to the console. However, I only see "Drawing Shape" printed twice. I suspect that the scenario might be related to object slicing or perhaps how I'm storing and invoking methods on the `shared_ptr`. I've tried changing the `std::vector` to hold raw pointers (`Shape*`), but that led to memory management issues, as I need to ensure proper cleanup. I also made sure that the `draw()` functions are marked as `virtual` and overridden correctly. Could someone guide to understand why the derived class's method isn't being invoked as expected? Is there a trick I'm missing regarding `std::shared_ptr` and polymorphism? Thanks! What would be the recommended way to handle this?