Dynamic_pointer_cast of shared_ptr in vector

Hello !

I have a class Forme with other class (Circle, Square, etc…) that inherite from Form like this:

class Forme {};
class Circle : public Forme {};
class Square : public Forme {};

then in the main I have a vector of shared_ptr of Forme:

std::vector<std::shared_ptr<Forme>> formes;

How can I modify or “dynamic_pointer_cast” a Circle object to a Square one inside my Vector ?
let’s say I want to change the 3th element of the vector from Circle to Square like this

formes[2] = std::dynamic_pointer_cast<Square>(formes[2]);

I think it has something to do with reinitialize the object after with “make_shared” but i’m not sure how exactly…

Thank’s for your help

Ok I found it !

I have to create a new pointer of the new Type from the actual one and then replace the old one.
like this:

std::shared_ptr<Square> newPtr = std::dynamic_pointer_cast<Square>(formes[2]);
formes[2] = std::make_shared<Square>();

maybe it can helps someone else…

1 Like