[fpc-pascal] casting back a pointer to original type
David Emerson
dle3ab at angelbase.com
Sat May 29 19:46:45 CEST 2010
> element := C(list[index]); // casting back
> text := element.text;
> I cannot do that, even if elements all are *indirect* instances of C, because
> this calls C.text instead of the element's own proper text method.
If you use virtual methods then C.text should call the descendant's method. This
is what polymorphism, the most powerful concept in object oriented programming,
is all about.
> Side-question: it seems, when subclassing, that methods with same name and
> same parameters do not need any modifier keyword (such as "override"
> or "overload"). Eg I can have
> function text;
> in both a superclass C0 and a subclass C1 work as expected. Correct?
This is likely your problem. If you are not using virtual methods then you are
not going to get polymorphism.
Here's a sample program to illustrate:
{$mode objfpc}
type
C0 = class
procedure statictext;
procedure virtualtext; virtual;
end;
C1 = class (C0)
procedure statictext;
procedure virtualtext; override;
end;
procedure C0.virtualtext;
begin
writeln ('C0 virtual');
end;
procedure C0.statictext;
begin
writeln ('C0 static');
end;
procedure C1.virtualtext;
begin
writeln ('C1 virtual');
end;
procedure C1.statictext;
begin
writeln ('C1 static');
end;
var
a : C0;
b : C1;
p : pointer;
t : tobject;
begin
b := C1.create;
p := b;
a := C0(p);
a.statictext; // output: C0 static
a.virtualtext; // output: C1 virtual
// let's add another degree of removal
t := tobject(p);
C0(t).statictext;
C1(t).statictext;
C0(t).virtualtext;
C1(t).virtualtext;
end.
Cheers,
David
More information about the fpc-pascal
mailing list