Why is 'virtual' optional for overridden methods in derived classes?

前端 未结 5 1815
走了就别回头了
走了就别回头了 2021-02-05 12:53

When a method is declared as virtual in a class, its overrides in derived classes are automatically considered virtual as well, and the C++ language ma

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-05 13:32

    That is a good question, and I certainly agree that it is good style to redeclare a method virtual in the derived class if it has been declared virtual in the base class. While there are some languages that build style into the language (e.g. Google Go and, to some extent, Python), C++ is not one of those languages. While it certainly is possible for a compiler to detect that a derived class does not reuse the keyword "virtual" for something declared "virtual" in a base class (or, more importantly, that the derived class declares a function of the same name as the base class and it has not been declared virtual in the base class), there are, in fact, settings on many compilers to issue warnings (and even error messages) in the event that this happens. At this stage, though, it would not be practical to institute such a requirement in the language as there exists too much code that is not that strict. Moreover, developers can always choose to be more stringent than the language and can turn up compiler warning levels.

提交回复
热议问题