Re: Inherited explained



Rudy Velthuis wrote:
Anonymous wrote:

procedure WMSysCommand(var Msg: TWMSysCommand); message
WM_SYSCOMMAND;

procedure TForm1.WMSysCommand;
begin
if (Msg.CmdType = SC_CLOSE) then begin // X button clicked in upper right hand corner of program interface
...do what needs to be done
end
else
inherited; //inherited means to do what you would have otherwise done
end;

"inherited;" on its own means here: call WMSysCommand(Msg) in the
ancestor class, but only if there is such a method in that class.
Otherwise, ignore the call.

In this case, it doesn't necessarily mean to call WMSysCommand. Rather, it means to call the next-less-derived method that's also marked with "message wm_SysCommand." The name of the method doesn't matter. And furthermore, if the ancestor doesn't have a wm_SysCommand handler, then it will call the virtual TObject.DefaultHandler method instead.

Now "inherited WMSysCommand(Msg);" would also have been possible, but
that would cause a compiler error if the ancestor does not have a
WMSysCommand.

And it could also lead to skipping over some method if there were another handler for the same message but that happened to use a different name.

Some examples:

type
TOne = class
procedure WMSysCommand(var Msg); message wm_SysCommand;
end;

TTwo = class(TOne)
procedure SysCommandHandler(var Msg: TWMSysCommand); message wm_SysCommand;
end;

TThree = class(TTwo)
procedure WMSysCommand(var Msg): message wm_SysCommand;
end;

procedure TOne.WMSysCommand;
begin
inherited; // Calls TObject.DefaultHandler(Msg)

inherited WMSysCommand(Msg); // Compiler error
end;

procedure TTwo.SysCommandHandler;
begin
inherited; // Calls TOne.WMSysCommand(Msg)

inherited WMSysCommand(Msg); // Call TOne.WMSysCommand(Msg)

inherited SyCommandHandler(Msg); // Compiler error
end;

procedure TThree.WMSysCommand;
begin
inherited; // Calls TTwo.SysCommandHandler(Msg)

inherited WMSysCommand(Msg); // Calls TOne.WMSysCommand(Msg)
end;

--
Rob
.


Quantcast