I'm trying to define class methods all inside of the class declaration in Free Pascal, which I haven't been able to find any examples of online. Currently I have to do it like so:
unit Characters;
{$mode objfpc}{$H+}
// Public
interface
type
TCharacter = class(TOBject)
private
FHealth, FAttack, FDefence: Integer;
procedure SetHealth(newValue: Integer);
public
constructor Create(); virtual;
procedure SayShrek();
function GetHealth(): Integer;
published
property Health: Integer read GetHealth write SetHealth;
end;
// Private
implementation
constructor TCharacter.Create;
begin
WriteLn('Ogres have LAYERS!');
end;
procedure TCharacter.SayShrek;
begin
WriteLn('Shrek!');
end;
procedure TCharacter.SetHealth(newValue: Integer);
begin
FHealth:= FHealth + newValue;
end;
function TCharacter.GetHealth() : Integer;
begin
GetHealth:= FHealth;
end;
end.
Is there any possible way to make this a little cleaner? Defining everything elsewhere looks messy and is unorganized.
To clarify, I'd like to do something along the lines of this:
TMyClass = class(TObject)
public
procedure SayHi();
begin
WriteLn('Hello!');
end;
end;
Instead of having to define it further down. Is that possible?
That is not possible in Pascal. It is just not allowed by its grammar.
It is a fundamental design in Pascal that units are divided in interface
(What can be done?) and implementation
(How is something done?).
The compiler reads all interface
sections before parsing the implementation
parts. You might know this from C language. implementation
could be described as *.c-files, whereas interface
is equivalent to *.h-files in C.
Furthermore such code would heavily decrease readability of interface
sections (f.i. class declaratons).
What benefits do you hope to get with that?