Search code examples
c++shared-ptrmultiple-inheritance

shared_ptr cast with multiple inheritance


I became a bit confused.

namespace Io
{
    class IDevice;
}

//...

namespace Sensor
{
    class IDevice;
}

//...

class ComplexDeviceHandler : public Io::IDevice, public Sensor::IDevice;

//...

std::vector<std::shared_ptr<Io::IDevice>> devices; //populated by objects of type ComplexDeviceHandler

//..

for (const auto& device : devices)
{
    std::shared_ptr<Sensor::IDevice> sensor = device; //obviously, error here
}

Both Io::IDevice and Sensor::IDevice are interfaces (sort of). What cast should I use to convert std::shared_ptr<Io::IDevice> to std::shared_ptr<Sensor::IDevice>. In this case, std::shared_ptr<Io::IDevice> stores an address of object of type ComplexDeviceHandler, which is a child of both types.


Solution

  • You need to first try to cast it to ComplexDeviceHandler*, check if it worked, and then it will be convertible to Sensor::IDevice*:

    for (const auto& device: devices)
    {
        if (auto sidptr = std::dynamic_pointer_cast<ComplexDeviceHandler>(device)) {
            std::shared_ptr<Sensor::IDevice> sensor = sidptr;
        }
    }