[fpc-pascal] object.ClassInfo.Create

Martin lazarus at mfriebe.de
Thu Jun 18 20:43:26 CEST 2009


Just got a question, to ensure I understand thinks correctly.

Let's start with stuff I definitely know (or think so).

Destructors are virtual/overriden, because they are called on the 
instance, and the instance may be assigned to a variable "foo: Tobject", 
which would call TObject.Destroy instead of TMyClass.Destroy.

Constructors don't (usually) need this, because the are (usually) called 
on a class (that is the classname usually appears hardcoded in the source)

on TComponent constructors are virtual, because when loading from 
resource, those objects are instantiated separately (with NewInstance() 
), and the constructor is called on an instance. So nothing new, the 
usual way of virtual methods

Now if I have a variable/value with classinfo?
AnyObject.ClassInfo => has the class info for it's class

BUT
TMyClass.Classinfo, could either be a TmyClass or a TMySubClass
(and per definition ClassInfo is TObject, and could be anything 
inherited from Tbject)

SO if I wrote
  FMyClass := AMyClass.Classinfo.Create;

What will actually happen?
If I understand this right, an instance of TMyClass (or TMySubClass , if 
AMyClass was a TMySubClass) is created; BUT the constructor 
TObject.Create is called (with then TMyClass instance) ?
And it would skip any constructor that was on TMyclass?

Then I could of course write
  TMyClassType = class of TMyClass;
  FMyClass := TMyClassType (AMyClass.Classinfo).Create;
and it would call TMyClass.Create. And if TMyClass wanted to have it's 
own constructor, the TMyClass.Create must be virtual?


How close am I do the truth?

Thanks
Martin




More information about the fpc-pascal mailing list