Re: Overriding/Redefining a Non-Virtual Function in Derived Classes
Michael K. O'Neill wrote:
In Scott Meyers' "Effective C++", item 36 states "Never redefine an
inherited non-virtual function". This admonition is repeated at item 23.8
of C++ FAQ Lite ("[23.8] Should a derived class redefine ("override") a
member function that is non-virtual in a base class?" at
http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.8 ).
I only just now recognized that in the MFC framework, this is done all the
time. Particularly with respect to message handlers for CWnd-derived
classes, it's common to see code like:
BOOL CDerivedWnd::OnEraseBkgnd(CDC* pDC)
{
// call base class function, which is not a virtual function
CWnd::OnEraseBkgnd(pDC);
// ... code specific to derived class
return TRUE;
}
I recognize that MFC is not a paragon of C++ good-programming
practices. It is also my understanding that the programming
of message handlers for CWnd-derived classes was an attempt to
*avoid* virtual functions.
Sounds like a bad design decision up front.
But given the fact that it is used so extensively by the MFC
framework, is it truly such a bad idea to override/redefine
non-virtual functions in derived classes? Is it truly
something that should be left to "experienced C++
programmers", as mentioned in the C++ FAQ Lite?
As usual, the answer is: it depends. Both Scott Meyers and the
author of the FAQ give reasons. Do these reasons apply to your
work? If not, why not?
IMHO, it's a good general rule, even if there are specific
idioms which violate it. It's something that I don't think
you'd want to do casually (or accidentally), but which is
perfectly appropriate if you are using one of the recognized
idioms which uses it.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]