Ways to detect whether a C++ virtual function has been redefined in a derived class

前端 未结 9 1449
不知归路
不知归路 2020-12-01 14:10

In brief: From a C++ base-class pointer which points to an instance of a derived class, how can one determine at run-time whether a non-pure virtual functio

9条回答
  •  时光说笑
    2020-12-01 14:27

    Even though this probably is somehow possible, I would advice not doing it. You are:

    • Violating the OOP principles. If you are given a general class/interface, you should not check for implementation details. This increases dependency between classes and is exactly the opposite of what OOP was designed for.
    • Duplicating code. Considering that you use the constants that would be otherwise returned by the Equation class.
    • Obfuscating code. Many conditions with type checks will make your program look ugly.
    • Probably doing a premature optimization. There is almost no speed difference between executing a virtual function call and a condition. Have you run your profiler to check if it's the virtual functions that are the bottleneck? It is almost never the case in a well designed application/library.

提交回复
热议问题