Is my method for avoiding dynamic_cast<> faster than dynamic_cast<> itself?

Implementations of dynamic_cast will of course vary by compiler.

In Visual C++, the vtable points to a structure which contains all of the RTTI about a structure. A dynamic_cast therefore involves dereferencing this pointer, and checking the "actual" type against the requested type, and throwing an exception (or returning NULL) if they are not compatible. It is basically equivalent to the system you describe. It's not particularity slow.

Your design also sounds a bit off - you have a factory method which forgets the true type of an object, then you immediately want to un-forget that information. Perhaps you should move that logic you do when unforgetting a type into the factory method, or into virtual methods on the base class itself.


The only correct answer to "is it faster" is "try it."


This depends on how you manage your messages. When I have a switch to select the message based on the type the best option is to use static_cast, as you know that the function parser will give you the create the correct type.

Message* gmsg parse(frame);

switch (gmsg->type) {
  case FooMessage_type:
    FooMessage* msg=static_cast<FooMessage*>(gmsg);
    // ...
    break;
  case BarMessage_type:
    BarMessage* msg=static_cast<BarMessage*>(gmsg);
    //...
    break;      
};

The use of dynamic_cast here is overprotecting.

Why do you need that all the messages inherits from a common one? What are the commonalities? I will add another design which doesn't use inheritance at all

switch (frame::get_msg_type(aframe)) {
  case FooMessage_type:
    FooMessage msg=parse<FooMessage>(aframe);
    // work with msg
    break;
  case BarMessage_type:
    BarMessage msg=parse<BarMessage>(aframe);
    //...
    break;
};

where parse parses a frame as a MSG, or throw an exception when the parse fails.

I see other answer that are telling you to use virtual functions. I really don't see any advantage to this OO design for messages.