Search code examples
c++structdowncast

Is there a way to down cast a struct to its derived one in C++?


Here is my situation:

struct A {
    int numberAllChildStructsUse;
}

struct B : A {
    std::string strUniqueToB;
}

struct C : A {
    std::string strUniqueToC;
}

(in some source file)

B b = thisFunctionReturnsBOrCStructsAsTypeA(int idThatGuaranteesItIsTypeBNotC);

Error: no suitable user-defined conversion from A to B exists when I try that above line. What is the best way to get this to work? Struct A represents the commonalities that all Bs, Cs share. The member vars inside of B and C are unique to each other. That function returns A type structs, but I know that they are actually in fact either Bs or Cs, and can tell based off of the parameter I supply.


Solution

  • You can use dynamic_cast for this, but only if the class hierarchy is polymorphic.

    To achieve the latter, write

    struct A {
        int numberAllChildStructsUse;
        virtual ~A() = default;
    };
    

    reference: https://en.cppreference.com/w/cpp/language/dynamic_cast