dimanche 1 octobre 2023

Always have std::bad_cast to dynamic_cast [duplicate]

I have the following code:

struct Attribute
{
    std::string key{};
    std::string value{};
};

struct Tag
{
    Tag* parent{};
    std::vector<Tag> children{};
    virtual void Dummy() {};
};

struct TagName : public Tag
{
    std::string name{};
    std::vector<Attribute> attributes{};
    void Dummy() override {};
};

struct TagValue : public Tag
{
    std::string value;
    void Dummy() override {};
};

int main()
{
    Tag tag{};
    
    TagName tn{};
    tn.name = "html";
    tn.attributes.push_back({"color", "black"});
    tag.children.push_back(tn);    // add a TagName

    TagValue tv{};
    tv.value = "lorepsum";
    tag.children.push_back(tv);    // add a TagValue

    std::cout << tag.children.size() << std::endl;                // display 2 elements

    TagName& name = dynamic_cast<TagName&>(tag.children.at(0));   // I always have bad_cast exception !?
    TagValue& val = dynamic_cast<TagValue&>(tag.children.at(1));  // I always have bad_cast exception !?

    return 0;
}

Why I always have bad_cast exception, even my tag.children.at(0) its a TagName type?

P.S. The code has not include try/catch handler, its not the purpose of the post.

Aucun commentaire:

Enregistrer un commentaire