sjrowlinson
sjrowlinson

Reputation: 3355

Segmentation fault when using dynamic_pointer_cast

The following code-snippet is a MWE of an issue I'm encountering with std::dynamic_pointer_cast:

#include <iostream>
#include <memory>

class foo {
private:
    int x;
public:
    foo() : x(0) {}
    foo(int xx) : x(xx) {}
    virtual ~foo() = default;
    int get_x() const { return x; }
};

class bar : public foo {
private:
    double y;
public:
    bar(double yy) : foo(), y(yy) {}
    double get_y() const { return y; }
};

int main(void) {
    bar b(0.5);
    std::shared_ptr<foo> fptr = std::make_shared<foo>(b);
    std::cout << (std::dynamic_pointer_cast<bar>(fptr))->get_x();
    return 0;
}

This program segfaults at the output stream line (std::cout << ...) presumably because the dynamic_pointer_cast is resulting in a nullptr, but I'm not sure why this is the case?

Any assistance is appreciated, plus here is a Coliru link to the snippet too.

Upvotes: 2

Views: 1097

Answers (1)

songyuanyao
songyuanyao

Reputation: 172924

This is expected behavior. fptr manages a pointer which pointing to a foo in fact. When you down-cast it to pointer to bar via dynamic_cast the cast would fail and you'll get a null pointer.

If fptr points to a bar then it'll work. e.g.

std::shared_ptr<foo> fptr = std::make_shared<bar>(b);

Upvotes: 3

Related Questions