Home > Articles > Programming > C/C++

  • Print
  • + Share This
From the author of

Inherited Fear

Traditional embedded developers dread inheritance even more than the creation of simple C++ classes. Inheritance has a bad reputation because the compiler must create a virtual function pointer table (vtable) to resolve which class contains the virtual function in question. By contrast, overloaded functions don't require a vtable entry because functions are handled at compile time via name mangling. Inheritance also forces the compiler to construct all of the class's ancestors when a class is declared, thus potentially creating an N-fold increase in code execution path (where N is the number of classes in the class hierarchy).

In reality, the determining factor for inheritance usage in an embedded environment is the complexity of your class hierarchy. The performance impact of inheritance isn't significant if your class hierarchy is simple (a parent class and some children). Although some overhead is associated with the vtable implementation, modern compilers offer optimization features to minimize this overhead if the hierarchy isn't too deep. By contrast, multiple inheritance and virtual base classes have a significant performance penalty and should be avoided (especially in interrupt service routines).

While multiple inheritance is bad, third-party templates and class libraries are even worse. Typically, these templates have a massive footprint and haven't been optimized for embedded usage. Therefore, they shouldn't be used in most embedded projects. If you absolutely must use templates (because you're porting code), you'll likely have to hand-prune the templates to remove extraneous functionality. Unfortunately, because most template libraries are closely integrated, it's not trivial to pull out only the portion you need.

  • + Share This
  • 🔖 Save To Your Account