Jump to content


Photo

class references


  • Please log in to reply
2 replies to this topic

#1 Nico Wouterse

Nico Wouterse
  • Moderators
  • 250 posts
  • LocationAustralia

Posted 02 September 2017 - 08:48 AM

I have a number of types of objects, all derived from the same parent object :

parentobject (unit):
Type
  TParentObject = class(TObject)
Type
  TParentObjectClass = class of TParentObject;
  
Object1 (unit):
type
  TObject1 = class(TParentObject)
  public
    procedure DoSomething;

Object2 (unit):
type
  TObject2 = class(TParentObject)
  public
    procedure DoSomething;

etc for a number of different types of objects
Now I can handle these objects of course like
var Object1 := TObject1.Create
Object1.DoSomething;
etc

but I want to have this generic for all objects.
Class referencing is supposed to allow for that,
and the following does indeed work :

var MyObject := TParentObjectClass.Create;
(MyObject as TObject1).DoSomething;
(MyObject as TObject2).DoSomething;
etc
What I want though is even more generic handling as in:

var MyObject := TParentObjectClass.Create;
and suppose I have all the different object classtypes stored in an ObjectClassArray : array of TParentObjectClass
then this should work
(MyObject as ObjectClassArray[i]).DoSomething;
except it doesn't

However if I check certain values of ObjectClassArray then these checks are true
For instance if the first array entry refers to Object2 then
If ObjectClassArray[0] = TObject2 then console.log('true'); logs true

Any ideas why I can't use the generic "(MyObject as ObjectClassArray[i]).DoSomething;" statement above

or an alternative method for what I want to achieve ?
Nico Wouterse

#2 Nico Wouterse

Nico Wouterse
  • Moderators
  • 250 posts
  • LocationAustralia

Posted 02 September 2017 - 09:26 AM

Found the answer.

Had to add

"procedure DoSomething; virtual;"

to TParentObject

parentobject (unit):
Type
  TParentObject = class(TObject)
    procedure DoSomething; virtual;
Type
  TParentObjectClass = class of TParentObject;
and add the 'override' directive to all TObjects

Object1 (unit):
type
  TObject1 = class(TParentObject)
  public
    procedure DoSomething; override;

Nico Wouterse

#3 Dennis07

Dennis07
  • Administrators
  • 24 posts
  • LocationBerlin, Germany
  • Enterprise Edition

Posted 02 September 2017 - 09:45 PM

Exactly, this is what virtual methods are used for. :) The keyword actually indicated that the medthod is identical with the ones declared in descending classes. What you could also use is the "TObject.ClassType" instead of declaring a separate "class of TObject" class reference, because it's actually a pointer with just a different type mask and name.
  • Nico Wouterse likes this




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users