开发者

C++: tall class hierarchies

开发者 https://www.devze.com 2023-01-28 12:51 出处:网络
What are the run time disadvantages of having a tall class hierarchy? Let\'s call H the height of the hierarchy (ie: how many classes are traversed to开发者_如何学Go go from the base class to a leaf)

What are the run time disadvantages of having a tall class hierarchy?

Let's call H the height of the hierarchy (ie: how many classes are traversed to开发者_如何学Go go from the base class to a leaf).

dynamic_cast will cost more: it costs O(H).

Are there other operators or language features suffering?


The main problem will be maintainability. A deep class hierarchy is probably not modeled correctly. Anything more than 3-4 levels should get you alerted. You are probably deriving from concrete classes, something you should never do (Liskov Substitution principle doesn't allow this). Refactoring will be difficult if your base classes are riddled with virtual functions (I mean not pure).

Split your base classes into several different interfaces (Interface Segregation). Prefer composition over inheritance (GoF fundamental rule of software design).

Personal advice: Try to program without dynamic_cast. I was able to program completely without dynamic_cast when I was a C++ developer. I used design patterns where appropriate, factories, visitors, etc. Life was much more simple without casts :-).

Good luck!


All the operations can be implemented in O(1) time, and usually they all are, except dynamic_cast. The last one can be implemented in O(1) time for statically linked libraries, see here.


the construction and destruction of objects of leaf classes take longer, as all constructors in the hierarchy are called (from the base class down to the leaf class).

0

精彩评论

暂无评论...
验证码 换一张
取 消