Jump to content
Sign in to follow this  
lynkfs@gmail.com

class references

Recommended Posts

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).DoSomething;" statement above

 

or an alternative method for what I want to achieve ?

Share this post


Link to post
Share on other sites

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;

Share this post


Link to post
Share on other sites

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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×