implement a virtual method from the base class as derived in static

感情迁移 提交于 2019-12-06 16:16:11

I do think that the FooStatic approach you have is the best way to go about it, in terms of adhering to good OO practice. Essentially, your non-static Foo overrides work like function pointers into your static versions.

(Emphasis on "work like": you can't actually use function pointers directly, since your override for Foo has to throw away the reference to this before invoking FooStatic.)

It would not make sense to make a virtual method static. Virtual means that you choose which implementation to run based on the type of an object. In a static context you have no object.

EDIT: While the first example will compile, it will not do what you expect it to do. The static methods will not override the base implementation, but rather hide it, meaning that the static methods will never be called instead of that of the base class. The second example is fine though, I cannot see any problem with it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!