[fpc-pascal] Cast, inheritance, etc
Marcos Douglas
md at delfire.net
Tue Dec 4 20:03:36 CET 2012
Hi,
See the code below.
My question is: Why the cast worked, considering the c variable is a
TAClass instance, not a TBClass.
-------------
program Project1;
{$mode objfpc}{$H+}
uses
Classes, SysUtils;
type
TAClass = class
protected
FInfoA: string;
public
constructor Create;
end;
TBClass = class(TAClass)
protected
FInfoB: string;
public
function GetInfoA: string;
function GetInfoB: string;
end;
{ TAClass }
constructor TAClass.Create;
begin
FInfoA := 'TAClass info';
end;
{ TBClass }
function TBClass.GetInfoA: string;
begin
Result := FInfoA;
end;
function TBClass.GetInfoB: string;
begin
Result := FInfoB;
end;
var
c: TAClass;
s: string;
begin
c := TAClass.Create;
try
// The c is a TAClass, not a TBClass instance!
// but worked... WHY?!
s := TBClass(c).GetInfoA;
writeln(s);
// Now I got an AV... ok for me.
writeln(TBClass(c).GetInfoB)
finally
c.Free;
end;
writeln('Done');
end.
Marcos Douglas
More information about the fpc-pascal
mailing list