Re: Homework question relating to docview
On Fri, 13 Jul 2007 15:23:13 GMT, "David Ching" <email@example.com>
"Doug Harrison [MVP]" <firstname.lastname@example.org> wrote in message
On Fri, 13 Jul 2007 13:44:37 GMT, "David Ching"
Well, I never thought of this as a problem because e.g. if I handle
WM_ERASEBACKGND, in that handler, I've always been able to call
CBaseClass::OnEraseBkgnd() and did not have to resort to SendMessage(). I
don't exactly know what magic makes that work.
When you say CBaseClass::OnEraseBkgnd(), you are defeating the virtual
mechanism, so "getting polymorphic behavior" doesn't apply. Indeed, you
don't want it when you call the base class version from the derived class,
and this is about the only legitimate scenario in which you can call a
normal, non-virtual message handler directly, by name.
Why is OnEraseBkgnd special?
It's not. What is special is calling it with the syntax
CBaseClass::OnEraseBkgnd(). This turns off the virtual call mechanism, so
even if OnEraseBkgnd were virtual, it would not be a virtual call, and you
would get the base class version. This is the correct syntax to use to call
the base class version from a derived class override for both virtual
functions and normal, non-virtual message handlers.
I don't know what you mean. When my handler merely adds to the behavior of
the base one, I also want the base's behavior. There's nothing about
"defeating the virtual call mechanism" about that.
Sure there is! If a derived class virtual function f somehow called its
base class version, and that call was virtual, you'd end up back in
derived::f, causing infinite recursion and stack overflow. That's why
derived::f has to call it with the base::f() syntax.
Of course, we were not talking about calling OnWhatever from
OnSomethingElse. We were talking about calling it from OnMyWhatever (the
handler in the derived class).
Of course, I began the discussion of this to explain that some OnXXX
functions such as OnSaveDocument are virtual and are meant to be called
from multiple places, while ordinary message handler functions are
non-virtual, and though similarly named, an OnXXX message handler must not
be called directly, by name, if polymorphic behavior is desired. Instead,
you have to use SendMessage to get polymorphic behavior out of a normal
message handler, which among other things, is a good reason for a function
such as OnSaveDocument to be virtual and not a message handler.
Visual C++ MVP