Question

Changing the type of class at runtime

Asked by: jaja2005

I have two class TFirts and TSecond. TSecond inherits from TFirsts.
User can create an object of type Tfirst at runtime. I want allow the
user later on to turn this object into a TSecond type. Can I do it?
Should I create a new TSecond object and then copy all the TFirst
fields to the second one?

Thx

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-11-03 at 11:48:25ID24868529
Tags

delphi

Topics

Delphi Programming

,

Delphi Components

,

Pascal Programming Language

Participating Experts
3
Points
500
Comments
13

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. RUNTIME_CLASS
    I derived CMyThread from CWinThread. Does RUNTIME_CLASS can create an object whose constructor has parameter? For example: CMyThread : public CWinThread { DECLARE_DYNAMIC(CMythread) protected: CMyThread(Object *); ~CMyThread(); } Also, another question is that: when I use R...
  2. RunTime Class Information
    CObject supports RunTime Class Information . What is this Runtime Class Information and what is its purpose?
  3. runtime polymorphism
    public class child extends base { int i=20; void m1() { System.out.println("child"+i); } public static void main(String args[]) { base a =new base(); base b=new child(); a.m1(); b.m1(); System.out.println("i1:"+a.i); System.out.println(...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: Geert_GruwezPosted on 2009-11-03 at 12:22:04ID: 25733143

don't think so

can you show what you want ?
maybe there is a way

 

by: KoenVandemoortelPosted on 2009-11-03 at 13:54:18ID: 25734212

Even if it could be done, it sure looks like bad practice.
I suggest you use a property that can be changed in runtime, to make your object's behavior change according to your needs.

 

by: epasquierPosted on 2009-11-03 at 14:25:26ID: 25734503

Well, if you have a lot of differences between TFirst and TSecond, it makes sense to not having a complicated TFirst object just in case a property 'Type' changes from typFirst to typSecond
I certainly would not mark this kind of work as 'not proper' or 'bad practice', it very much depends on the use case.

add a method or two like :

procedure TFirst.Assign(tf:TFirst);  // Copy all TFirst fields from one instance to the other. Maybe override it in TSecond if you have some other initializations to make when TSecond get content from TFirst

constructor TSecond(tf:TFirst); // Will essentially call Assign

For those who are not yet sure that this is not a bad practice, here are the advantages :
- why reserving a lot of memory when you only need a few properties when the object is on a 'lower' state
- a property "Type" that could change in real-time would have to implement every aspect Assign does, but  "flatening" the inheritance. Besides, it would assume that going from type1 to type2 and from type2 to type1 again is of little consequence. It might not be what is needed, and 2 classes (or more) can emphasize those (needed) aspects, and ease implementation
- the overhead of copying a few fields is not an argument, as it is not likely to happen often.

If it's done right, this kind of "upgrade"  of objects can be very convenient and efficient

 

by: epasquierPosted on 2009-11-03 at 14:26:38ID: 25734510

forgot the Create :

constructor TSecond.Create(tf:TFirst); // Will essentially call Assign

 

by: epasquierPosted on 2009-11-03 at 14:36:04ID: 25734597

I forgot the main black point of this : You can't have many references to the object, otherwise it's going to be a nightmare to update all new pointers to the new upgraded object.

But that is not much of a problem because
a) it's always a bad idea to have multiple references to the same object, except for localized methods during a process, which is unavoidable.
b) the objects that needs this kind of subterfuge most certainly needs already to be gathered in a collection of some sort (TObjectList), and they are always accessed through this list. So there is just one place to update, and this can be done in single Constructor/Destructor :

Constructor TSecond.UpgradeFrom(tf:TFirst);
begin
 Assign(tf);
 MyObjectList.Insert(MyObjectList.Remove(tf),Self);
 // Automatically free tf (with MyObjectList.OwnsObject:=True) 
 // and insert the new object in its exact position
end;

                                              
1:
2:
3:
4:
5:
6:
7:

Select allOpen in new window

 

by: jaja2005Posted on 2009-11-04 at 00:29:19ID: 25737371

Hi! Thanks for you relply.
What's happen if I do:

Var obj1 : TMyObj1;
Var ObjBase : TBase;

Type
TMyObj1 = class (TBase)
.....
end;

ObjBase := TBase.Create;

later on in the code:

Obj1 := TMyObj1(ObjBase); ????


 



 

by: epasquierPosted on 2009-11-04 at 03:02:48ID: 25738088

until you don't call any specific methods of TMyObj1, this will not complain.
a cast does not transform your object, it just allow (trying) access your object as another. You have to be very sure that everything you do after with this casted object is allowed by the base object.
So, you will have no gain, and you risk having loads of trouble by confusing yourself.

 

by: epasquierPosted on 2009-11-04 at 03:06:24ID: 25738104

say for clarity, you have a property in TMyObj1 that is not there in TMyBase :

TMyObj1 = class (TBase)
private
  _Prop:Integer;
public
 property Prop:integer read _Prop write _Prop;
end;

if in your code you do
Obj1 := TMyObj1(ObjBase); ?
Obj1.Prop:=10;

this will compile, but on the property setting you will have an access violation error : you try to read a memory zone that is outside the memory block pointed by your ObjBase object

 

by: epasquierPosted on 2009-11-04 at 03:18:43ID: 25738171

I guess you are trying to build an electronic scheme editor, so you will have to handle a bunch of basic components, that can have a different number of pins or specific properties. So You might want to manage what kind of transformation is possible, and what properties can be salvaged from the older component to the new one.
Creating a supercomponent with all possible properties is probably the best way to throw yourself through the window in a few month, as you will maybe have to implement some "virtual testing" of these scheme, or some other complex operations. You have to have different classes, and you have also the need for ugrade, so....

no, really, what you have to do is implementing an UpgradeFrom virtual method in your base class, to manage all common fields and when needed override and/or overload it to manage different pairs of transformation (from TypeA to TypeB)

 

by: jaja2005Posted on 2009-11-04 at 03:42:20ID: 25738310

...robably the best way to throw yourself through the window in a few month

not good. :-)

no, really, what you have to do is implementing an UpgradeFrom virtual method in your base class, to manage all common fields and when needed override and/or overload it to manage different pairs of transformation (from TypeA to TypeB)

An object of typeB may have a method i.e. DoSomeTask (implemented using interface) which is not part of TypeA definition. The DSomeTask procedure collect some date and do some calculation as well in order to valorize the propreties of TypeB object. So, the user may want to create for instance a node of typeA and then later on turn it into TypeB without loosing previous values (the ones of the baseclass). So I will be glad if you may guide me step by step on how to implement this virtual method. I caught what you have suggested at 60% :-)) some code may be helpful.
thx

 

by: epasquierPosted on 2009-11-04 at 04:28:18ID: 25738611

>> So, the user may want to create for instance a node of typeA and then later on turn it into TypeB
>> without loosing previous values (the ones of the baseclass)

Yep, that's the Assign principle

Let's say :

TBaseClass=class
private
 _P1:Integer;
 _P2:String;
 _P3:TObjectList; // a container is tricky
public
 
 procedure Assign(B:TBaseClass);

 property P1:Integer read _P1;
...
end;

TNewClass=class(TBaseClass)
private
 _P4:Integer;
...

end;


procedure TBaseClass.Assign(B:TBaseClass);
Var
 i:integer;
begin
 _P1:=B._P1;
 _P2:=B._P2;
// _P3:=B._P3; // Dangerous, P3 is a container. If you clear one, the other will be cleared. If you free one, the other will be invalid and raise exceptions
// correct way of doing it :
 _P3.Clear;
 for i:=0 to B._P3.Count-1 do
   _P3.Add(B._P3[i]); // still dangerous with objects if P3 is a container that owns objects, Ok otherwise
// or something like :
   _P3.Add( TBaseItem(B._P3[i]).CreateCopy ); // CreateCopy is a "constructor" that copy values from the caller object (like Assign), and must be implemented in the TBaseItem
end;


You can call then
NewObject:=TNewClass.Create;
NewObject.Assign(OldObject);

and do all in one pass in a new constructor for NewClass calling the Assign with an old object passed as parameter.

 

by: jaja2005Posted on 2009-11-04 at 04:32:35ID: 31649608

Well done.

 

by: jaja2005Posted on 2009-11-20 at 05:56:50ID: 25870213

KoenVandemoortel:

Even if it could be done, it sure looks like bad practice.
I suggest you use a property that can be changed in runtime, to make your object's behavior change according to your needs

Hi Koen.
Could you please show me an example?:-((

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...