I have to brush up on Virtual Methods for an interview. I understand them but got stumped when trying to demonstrate it to myself. First, go here: The example is in C++ so I converted it to delphi.
According to this article, removing the [red]//[/red] comment from the code should produce different results, but it doesn't. What am I missing here?
Roo
Delphi Rules!
Code:
unit AnimalUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
TAnimal = class
function eat: string; [RED]//virtual;[/RED]
end;
TWolf = class(TAnimal)
function eat: string;
end;
TFish = class(TAnimal)
function eat: string;
end;
TOtherAnimal = class(TAnimal)
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
function TAnimal.eat: string;
begin
result:= 'I eat like a generic Animal.'
end;
function TWolf.eat: string;
begin
result:= 'I eat like a wolf!'
end;
function TFish.eat: string;
begin
result:= 'I eat like a fish!'
end;
procedure TForm1.Button1Click(Sender: TObject);
var
Animal: TAnimal;
Wolf: TWolf;
Fish: TFish;
OtherAnimal: TOtherAnimal;
begin
Animal:= TAnimal.Create;
Wolf:= TWolf.Create;
Fish:= TFish.Create;
OtherAnimal:= TOtherAnimal.Create;
Memo1.Lines.Add(Animal.eat);
Memo1.Lines.Add(Wolf.eat);
Memo1.Lines.Add(Fish.eat);
Memo1.Lines.Add(OtherAnimal.eat);
Animal.Free;
Wolf.Free;
Fish.Free;
OtherAnimal.Free;
end;
end.
Roo
Delphi Rules!