-1

I have the following code, how to cast correctly from unique_ptr to base class?:

class MagEventNotifierAndSupplier : public CSubject,
    IMagneticData
{
public:
//implement
}
unique_ptr<MagEventNotifierAndSupplier> m_MagEventNotifierAndSupplier;
m_MagEventNotifierAndSupplier = make_unique<MagEventNotifierAndSupplier>("test");
IMagneticData* data= static_cast<IMagneticData*>(&m_MagEventNotifierAndSupplier);// invalid cast
YAKOVM
  • 9,805
  • 31
  • 116
  • 217

1 Answers1

1

You can't static_cast a unique_ptr* pointer to a IMagneticData* pointer, as they are unrelated types.

You don't need a cast at all. Since MagEventNotifierAndSupplier derives from IMagneticData, a MagEventNotifierAndSupplier* pointer can be assigned directly to an IMagneticData* pointer without casting.

You can get a MagEventNotifierAndSupplier* pointer from a std::unique_ptr<MagEventNotifierAndSupplier> object via its get() method, eg:

class MagEventNotifierAndSupplier : public CSubject, public IMagneticData
{
public:
    //implement
};

auto m_MagEventNotifierAndSupplier = std::make_unique<MagEventNotifierAndSupplier>("test");
IMagneticData* data = m_MagEventNotifierAndSupplier.get();
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770