[fpc-pascal] object.ClassInfo.Create
Marc Weustink
marc at dommelstein.net
Fri Jun 19 00:33:45 CEST 2009
Martin wrote:
> 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
It's not only for streaming, there are more common cases where you might
need virtual constructors:
var
GraphicClass: TGraphicClass;
Graphic: TGraphic;
begin
case Something of
1: GraphicClass := TBitmap;
2: GraphicClass := TPNGImage;
...
end;
Graphic := GraphicClass.Create;
...
end;
>
> 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)
Correct.
> SO if I wrote
> FMyClass := AMyClass.Classinfo.Create;
>
> What will actually happen?
It creates an instance of your class, but calls TObject.Create
> 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?
Correct.
> 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?
No, you don't need a virtual constructor here yet, since the
TMyClass.Create will be called. However if you have TMySubClass too with
an own create, you need one.
> How close am I do the truth?
Close :)
Marc
More information about the fpc-pascal
mailing list