jeudi 4 janvier 2018

C++ shared pointer with derived class

I am trying to get shared pointers of a base class from a derived class. Here's the code:

class Base {
    public:
    typedef std::shared_ptr<Base> Ptr;
    Base();
    Base(const Base& orig);
    virtual Ptr getShared() = 0;
};


class Derived : public Base {
    public:
    // default constructor and copy constructor
    virtual Base::Ptr getShared() {
        return std::make_shared<Derived>(this);
    }
};

I am trying to use it to get a vector of Base::Ptr, like so:

std::vector<Base::Ptr> objects;
Derived d;
objects.push_back(d.getShared()); 

I'm running into problems with the copy constructor, and I know this has to do with breaking const-correctness by trying to cast a pointer to a ref behind the scenes. I just can't pinpoint what the cause is, or I'm making a wrong assumption. Any thoughts?

Base.h:20:5: note: no known conversion for argument 1 from 'Base*' to 'const Base&' Base.h:19:5: note: candidate: Base::Base()

Aucun commentaire:

Enregistrer un commentaire