0

This is a question of pure curiosity, I don't think the answer could cause great improvements.

Let suppose there is this tree of inheritance:

           A
          / \
         /   \
       AB     AC
      /\       /\
  ABB  ABC   ACB ACC 

I have to write a function that executes differents actions basing on the object type. I'm 100% sure that this object can only be an AC object or one of its childs.

now which code is faster:

 int t = getObjectType();
 A*  obj = getObject();
 switch (t) {
      case 0:
         ACB* casted_obj = static_cast<ACB*>(obj);
      case 1:
         ACC* casted_obj = static_cast<ACC*>(obj);
 }

or

 int t = getObjectType();
 A*  sup = getObject();
 AC* obj = static_cast<AC*>(sup);
 switch (t) {
      case 0:
         ACB* casted_obj = static_cast<ACB*>(obj);
      case 1:
         ACC* casted_obj = static_cast<ACC*>(obj);
 }

Probably C++ standards doesn't say anything about how the tree of inheritance must be managed, so the answer depends on the implementation.

Clynamen
  • 509
  • 1
  • 6
  • 16

1 Answers1

2

Static casts are done entirely at compile time, so the performance impact will always be zero. The only type cast done at run time is dynamic_cast. More: http://www.cplusplus.com/doc/tutorial/typecasting/

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Paul Manta
  • 30,618
  • 31
  • 128
  • 208
  • That's not true. For example, if there are multiple base classes, then `static_cast` can change the value of the pointer. – Mike Seymour Jul 26 '12 at 14:40