jeudi 5 avril 2018

C++11 std::dynamic_pointer cast behaviour

I have some classes that are derived from each other and inherit their parents attributes, all under a common interface, simplified:

class I 
{
};

class A : public I
{
    data getDataA() const;
    data A_;

};

class B : public A
{
    data getDataB() const;
    data B_;
};

Now what I was hoping to achieve is the following.

  • I can create pointers of the interface class and move the objects/pointers around. auto p = std::shared_ptr<I>(new B(data));
  • When I need to access the data, I cast them to the needed data type, which works even if I dont need all of the data (eg I only need A_). auto a = std::dynamic_pointer_cast<A>(p);
  • When I need data that the particular object does not hold, I would expect to get an exception.

However casting works fine, I then get segmentation fault when accessing the data. Am I using the wrong cast?

Is this bad practice? Any hints on how this would be implemented better?

Aucun commentaire:

Enregistrer un commentaire