mardi 1 septembre 2015

std::dynamic_pointer_cast of std::shared from base to derived returns NULL

I have a function that accepts a shared pointer of type Base and then std::dynamic_pointer_cast to a derived type. However, the derived pointer is a NULL type and I can't see why. I have made sure to include a virtual destructor in my base class. I do not want to use a static cast as this cannot guarantee that my derived member variables and functions are preserved?

The code is as follows:

Base Class:

class Base
{
public:
    mType get_type()
    {
        return msg_type;
    }

    void set_type(mType type)
    {
        msg_type = type;
    }

    virtual ~cMsg() = default;
protected:
    mType msg_type;
    message msg;
};

Derived Class:

class Derived : public Base
{
public:
    void set_i(int j)
    {
        i = j;
    }

    int get_i()
    {
        return i;
    }
private:
    int i;
};

Function performing cast:

void callback(std::shared_ptr<Base> msg_received)
{
    std::cout<< "Callback called\n";
    auto real_msg = std::dynamic_pointer_cast<Derived>(msg_received);

    if (real_msg != NULL)
    {
        std::cout << "i value is: " << real_msg->get_i() << "\n";
    }

}

Function creating the Derived object and calling the function:

int main()
{  
    Derived test_msg;

    test_msg.set_i(1);    
    test_msg.set_type(mSystem::TEST_MSG);

    std::shared_ptr<Base> msg_ptr = std::make_shared<Base>(test_msg);    

    callback(test_msg);

    return 0;
}

Any help would be appreciated.

Aucun commentaire:

Enregistrer un commentaire