简体   繁体   中英

Polymorphism with smart pointers?

I've searched SO a bit but couldn't find anything that answers correctly my problem (I've read this , this and this )

I'm currently trying to use smart pointers with polymorphism.

When I try to create a smart pointer to an abstract class with a pointer to an implementation, ie :

std::shared_ptr<Abstract> ptr = std::make_shared(new Implementation);

My compiler (MSVC2012) displays errors about creating an instance of Abstract which is not possible because it has pure virtual, even though I try to create a pointer to Implementation .

I might just use smart pointers completely wrong in this case, but then I don't know what I did wrong (and Visual Studio doesn't underline the line I mentionned).

I wonder then if it is possible to use smart pointers when polymorphism is needed, and if yes, how it must be done.

Note : I know about covariance, and the fact that shared_ptr is not a type that inherit shared_ptr, but thought smart pointers would handle this.

EDIT :

As requested, the real line of code is :

std::shared_ptr<ISpectrometer> ret = std::make_shared<OOSpectrometer>(m_spectroWrapper);

With OOSpectrometer that inherit from the abstract class ISpectrometer (and m_spectroWrapper a simple parameter).

The error MSVC gives me (it's in french, so that could be different from the english message) is

error C2259: OOSpectrometer : can't instantiate an abstract class due to the following members :

And then it lists the pure virtual functions that are in ISpectrometer .

The problem is not with any broken behavior of std::shared_ptr with respect to polymorphism, and this error message is pretty clear:

error C2259: OOSpectrometer : can't instantiate an abstract class due to the following members :

Your class OOSpectrometer cannot be instantiated because it is abstract. Most likely, it does not implement all the pure virtual functions defined in the ISpectrometer interface.

Also, the list of pure virtual member functions which are not overridden by OOSpectrometer should be part of the error message your are getting (" due to the following members: ... ").

As the error message says, the problem is that OOSpectrometer is still abstract, not that it's trying to instantiate the abstract base class.

Check that you've correctly overridden all the pure virtual functions declared in ISpectrometer ; especially the ones listed in the error message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM