tags:

views:

183

answers:

2
TBase = class(TObject)
...

TDerived = class(Tbase)
...

if myObject is TBase then ...

can I code this somehow and have it return false if myObject is of class TDerived?

+12  A: 

If you need exact class type check use ClassType method:

type

TBase = class(TObject)
end;

TDerived = class(Tbase)
end;

procedure TForm1.Button1Click(Sender: TObject);
var
 A: TBase;

begin
  A:= TBase.Create;
  if A.ClassType = TBase then ShowMessage('TBase');  // shown
  A.Free;
  A:= TDerived.Create;
  if A.ClassType = TBase then ShowMessage('TBase again'); // not shown
  A.Free;
end;
Serg
A: 

You can use ClassType method, or just check PPointer(aObject)^=aClassType.

begin
  A:= TBase.Create;
  if A.ClassType = TBase then ShowMessage('TBase');  // shown
  if PPointer(A)^ = TBase then ShowMessage('TBase');  // shown
  A.Free;
  A:= TDerived.Create;
  if PPointer(A)^ = TBase then ShowMessage('TBase again'); // not shown
  if A.ClassType = TBase then ShowMessage('TBase again');  // not shown
  A.Free;
end;

If your code is inside a class method, you can use self to get the class value:

class function TBase.IsDerivedClass: boolean;
begin
  result := self=TDerivedClass;
end;
A.Bouchez
Poking in VMT internals, specially without using proper constants is FPC incompatible. Better use classtype
Marco van de Voort
FPC uses the same definition: ClassType is just a class function which returns TClass(Pointer(Self)). So using PPointer(AAobject)^ should be FPC compatible.
A.Bouchez