Search code examples
c++structdowncast

C++ Downcasting a struct


I have the following code:

struct Operation {
    public :
        OperationName name;
};

struct FilterOperation : Operation {
    FilterName filter;
    std::list<std::string> params;
};

The OperationName and FilterName are enums listing all the different names of each Operation and Filter.

In a for each loop going though all the Operations, I want to downcast a Operation to a FilterOperation:

std::list<Operation> operations
for (Operation op : operations) {
switch (op.name) {
    case o_filter :
        std::cout  << dynamic_cast<FilterOperation*>(&op)->filter << std::endl;
    }
}

Obviously the dynamic_cast doesn't work here:

parser.cpp:154:90: error: cannot dynamic_cast ‘& op’ (of type ‘struct Operation*’) to type ‘struct FilterOperation*’ (source type is not polymorphic)
 "Op: Filter, Name: " << filterStrings[dynamic_cast<FilterOperation*>(&op)->filter] 

I actually tried adding a virtual function to it, but that doesn't resolve my actual issue (I can't figure out how to downcast here properly)


Solution

  • Your intuition about adding a virtual function should have resolved the compiler error for you. Are you sure you didn't get some other error?

    In any case, because you are dealing with instances of objects rather than pointers, this will never work. Your list consists of Operation objects, not FilterOperation objects. If you want to insert FilterOperation objects then you need a list of pointers (or preferably, shared_ptr) instead of storing by value:

    std::list<Operation*> operations
    for (Operation* op : operations) {
    switch (op->name) {
        case o_filter :
            std::cout  << dynamic_cast<FilterOperation*>(op)->filter << std::endl;
        }
    }
    

    Additionally, I suspect you misunderstand what switch() will do for character strings. It will probably not do what you want, and you need an if statement instead.