[fpc-pascal] Class reference doubt
Dimitri Smits
smitco at telenet.be
Fri Nov 25 11:50:12 CET 2011
----- "Luiz Americo Pereira Camara" <luizmed at oi.com.br> schreef:
> On 24/11/2011 19:34, Jonas Maebe wrote:
> > In that case, you did not hit the same problem as the original
> poster (your "I also hit this problem recently" is what triggered my
> response). His problem was that if you call a non-virtual constructor
> on a class reference variable, that the constructor is determined
> based on the static type of the class reference rather than on the
> dynamic type.
>
> It does not matter much but i hit the same problem. Just replace class
>
> of TObj by class of TObject (TClass)
>
> I stored a class (TMyClass) in a class variable (AClass: TClass). I
> was
> expecting that calling AClass.Create would call TMyClass.Create. Just
>
> like him i found that is not the case.
>
> To be clear: i'm not saying that is a bug or asking for changing the
> behavior
>
so you have:
====
type
TMyObject=class(TObject)
...
constructor Create;
end;
TMyClass = class of TMyObject; // <-- important I guess
...
procedure processSomething(AClass: TClass);
var
someInstance: TObject;
begin
someInstance := AClass.Create(); // <-- always the one from TClass/TObject?
end;
...
begin
processSomething(TMyObject);
end;
====
class methods (and the constructors and destructor) are in Delphi part of the TClass memorystructure. I believe even the TObject default Create. For your trick to work, you need one of 2 things:
- declare the class-reference for a type explicitly (class of T...)
- make a virtual constructor in a subtype of TObject and declare a class-reference. Then you derive from that subtype.
I don't think (did not test) it finds a TMyClass in Delphi as well if you do not declare the type, so in effect it always takes TClass. The other scenario's I've used before in classfactory pattern before.
It has nothing and everything to do with RTTI. No, the new D2010+ RTTI does not give access to the default constructor (I think), but it IS part of the TClass-alike-structure that is generated for the TObject descendant.
kind regards,
Dimitri Smits
More information about the fpc-pascal
mailing list