“As a rule of thumb, make all your methods virtual” in C++ - sound advice?

前端 未结 5 1017
野性不改
野性不改 2021-01-07 23:38

I just happened upon the statement in the title. The full quote is:

As a rule of thumb, make all your methods virtual (including the destructor, but

5条回答
  •  死守一世寂寞
    2021-01-08 00:19

    I don't agree with the principle.

    In the past, some were concerned about overuse of virtual due to performance concerns. This is still somewhat valid, but not overly problematic on today's hardware. (Keep in mind, most other languages incur similar penalties these days. For instance, the 400MHz iPhone 2G used Objective C which incurs a virtual method call on every function call.)

    I think you should only use virtual on methods where it seems useful and reasonable to want to override it in a subclass. To me, it serves as a hint to other programmers (or your future self) as "this is a place where subclasses can sensibly customize behavior." If replacing the method in a subclass would be confusing or weird to implement, don't use virtual.

    Also, for simple setters and getters, it's probably a bad idea as it will inhibit inlining.

提交回复
热议问题