[fpc-pascal]Class Identification?

memsom at interalpha.co.uk memsom at interalpha.co.uk
Mon Mar 24 17:36:31 CET 2003


Michael,

> This is not entirely correct.

Neither is your explanation ;-)

> The latter will return false for a descendent of TButton, while the
> former will give true. The exact statement corresponding to the
> 'is' operator is

"The is and as operators use InheritsFrom in their implementations. The is 
operator, however, can only determine the inheritance relationship of an 
instance."

So it would not be exactly the same in all instances.

Besides, the original poster missed the point of inheritence and polymorphism 
by asuming that classtype was a good way to to run time type checking. Consider 
the following generic example:

TTranslationType = (ttRaw, ttWav, ttMP3 ...);

TTranslator = class
  function Translate(sin, sout: TStream): boolean; virtual; abstract;
  function getTranslatorType: TTranslationType;
end;

TWAVTranslator = class(TTranslator)
  function Translate(sin, sout: TStream): boolean; override;
end;

TMP3Translator = class(TTranslator)
  function Translate(sin, sout: TStream): boolean; override;
end;

TTranslatorClass = class of TTranslator;

TTranslatorFactory = class
  ...
  procedure RegistreTranslator( newclass: TTranslatorClass );
  function  FindTranslator( translatorType: TTranslationType; 
                            translator: TTranslator): boolean;
  ...
end;

var
  Factory: TTranslatorFactory = nil; //constructed in the initialization

...
var
  i, o: TFileStream;
  t: Translator;
  ...
begin
  Factory.RegisterTranslator(TWAVTranslator);
  Factory.RegisterTranslator(TMP3Translator);
  ...
  if ( Factory.FindTranslator( ttMP3, t) ) then begin
    t.Translate( i, o );
    ...
  end
  else
    raise Exception.Create('No Translator found'); 
  ...
end;
..

You don't *need* to know the type of the class instance the factory returns, 
just that it supports the functionality you requested... Interfaces make this 
much nicer ;-) However, if you use the _is_ operator, the code will be a lot 
less complex if you did need to find the class type. The other thing worth 
noting is that the _is_ and _as_ operators work the same with Interfaces as 
they do with classes... THIS is why you should use them.
  
> if myinst.Inheritsfrom(TButton) then ... ;

The main difference is that it clearly stated in the D5 help that one should 
*not use* ClassType in the fashion indicated by the original poster. 

Matt

---------------------------------------------
This message was sent using Mistral WebMail.
http://www.mistral.co.uk/





More information about the fpc-pascal mailing list