A B
A B

Reputation: 1521

confusing Inheritance using RTTI

pardon me if the question is not as per the rules but due to curiosity I just want to know why my objects classtype is making me confuse.

please see the below code:

 type 
 TFirstClass = class
 end;

  TSecondClass = class(TFirstClass)
  end;

  TThirdClass = Class(TSecondClass)
  End;

the above is my class structure.

In one method I just want to check class type of the class object.

    var
      obj1: TFirstClass;
      obj2: TSecondClass;
      obj3 : TThirdClass;
      str: string;
    begin
      obj1 := TSecondClass.Create;
      obj2 := TThirdClass.Create;
      try
    if obj1 is TFirstClass then
        str  := str + ' obj1: first ||';

    if obj1 is TSecondClass then
        str  := str + 'obj1 : Second ||';

    if obj2 is TSecondClass then
        str  := str + 'obj2 : Second ||';

    if obj2 is TThirdClass then
        str  := str + 'obj2 : Third ||';

    ShowMessage(str);
   finally
        FreeandNil(Obj1);
        FreeandNil(Obj2);
      end;

    end;

but the result in str is obj1: first ||obj1 : Second ||obj2 : Second ||obj2 : Third ||

Why is keyword returning true for all if statement?

Upvotes: 2

Views: 108

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 597941

TThirdClass derives from TSecondClass, which derives from TFirstClass. As such:

  • obj1 is just a TFirstClass by itself.

  • obj2 is a TSecondClass WHICH IS ALSO a TFirstClass.

  • obj3 (had you instantiated it) is a TThirdClass WHICH IS ALSO a TSecondClass WHICH IS ALSO a TFirstClass.

The is operator looks at the entire inheritance hierarchy, and returns True if the requested class type is found. If you want to do exact class matches, you need to compare the class types directly, eg:

if obj1.ClassType = TFirstClass then
  ...

if obj1.ClassType = TSecondClass then
  ...

if obj2.ClassType = TSecondClass then
  ...

if obj2.ClassType = TThirdClass then
  ...

Upvotes: 5

David Heffernan
David Heffernan

Reputation: 613441

The documentation has the answer:

The is operator, which performs dynamic type checking, is used to verify the actual runtime class of an object. The expression:

object is class

returns True if object is an instance of the class denoted by class or one of its descendants, and False otherwise.

They key phrase is "or one of its descendants".

Upvotes: 7

Related Questions