Let's say that I have:
type
TClassA = class
function prova: integer; virtual;
function provaSuA: integer; virtual;
end;
type
TClassB = class(TClassA)
function prova: integer; override;
function provaSuB: integer; virtual;
end;
Then I use this code:
procedure TForm1.Button1Click(Sender: TObject);
var a: TClassA;
b: TClassB;
begin
Memo1.Clear;
a := TClassB.Create;
try
b := ?? //dynamic_cast on C++
Memo1.Lines.Add(a.prova.ToString);
Memo1.Lines.Add(b.provaSuB.ToString);
finally
a.Free;
end;
end;
I am using polymorphism and the static type of a is TClassA
but the dynamic type is TClassB
. Of course I can only call on a
methods that are declared on TClassA
(or that are overridden in TClassB
).
If I want to use a
and have access to ALL methods in TClassB in C++ I'd use a dynamic_cast
that is (together with typeid) in C++ RTTI. How can I use Delphi's RTTI to do that?
Delphi "RTTI" has a slightly different meaning from C++'s one. To replicate what dynamic_cast
does, you need to follow one of the two patterns:
pattern 1: if the cast fails, I want an exception : this is achieved, by using the as
operator which performs the proper type-checking and then casts the object when possible. In case of failure, a ClassCastException
is thrown.
b:= a as TClassB;
pattern 2: if the cast fails, I want to handle it manually : this is achieved by using the is
operator which strictly performs the test about the cast. Then you are need to manually cast (look comments in code) on success:
if (a is TClassB) then begin // this is a cast, however, in this context, you are simply interpreting // the memory pointed by a as a class of type ClassB. You are not using any operator. b:= TClassB(a); end else begin // here you know that a cannot be cast to TClassB, therefore you can gracefully take // proper action here, without catching any exception end;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.