home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!zaphod.mps.ohio-state.edu!darwin.sura.net!dtix!oasys!roth
- From: roth@oasys.dt.navy.mil (Pete Roth)
- Newsgroups: comp.lang.pascal
- Subject: Polymorphic Poser
- Message-ID: <29121@oasys.dt.navy.mil>
- Date: 30 Dec 92 18:51:06 GMT
- Reply-To: roth@oasys.dt.navy.mil (Pete Roth)
- Organization: The David Taylor Model Basin
- Lines: 82
-
- I must have left my brain home...
-
- What I want to do is shown in the example code below. In words:
- Given the pointer to a derived object P,
- and Q declared as a pointer to an ancestor object type,
- HOW DO I INSTANTIATE Q AS A CLONE OF P ???????
-
- Going crazy...
- -----Cut-here--------Cut-here--------Cut-here--------Cut-here-------Cut-here----
- uses Objects;
-
- type
- PBase = ^TBase;
- TBase = object(TObject)
- constructor Init;
- constructor Clone( B : TBase ) ;
- function IsA : STRING ; VIRTUAL ;
- end;
-
- PDerived = ^TDerived;
- TDerived = object(TBase)
- constructor Init;
- constructor Clone( D : TDerived ) ;
- function IsA : STRING ; VIRTUAL ;
- end;
-
- constructor TBase.Init;
- begin
- inherited Init;
- end;
-
- constructor TBase.Clone( B : TBase ) ;
- begin
- Self := B ;
- end ;
-
- function TBase.IsA : STRING ;
- begin
- IsA := 'TBase'
- end ;
-
- constructor TDerived.Init;
- begin
- if not inherited Init then
- Fail;
- end;
-
- constructor TDerived.Clone( D : TDerived ) ;
- begin
- Self := D ;
- end ;
-
- function TDerived.IsA : STRING ;
- begin
- IsA := 'TDerived'
- end ;
-
- var
- P, Q, R: PBase ;
- begin
- P := New(PDerived, Init);
- if P <> nil then begin
- Writeln( 'P is a ', P^.IsA ) ;
- { how do I write a statement that instantiates Q as a PDerived
- without specifying that TYPE, and without typecasting the Clone
- method ? For example: }
- Q := New( PDerived, Clone( PDerived(P)^ )) ;
- Writeln( 'Q is a ', Q^.IsA ) ;
- { works, but what I really want is something like
- R := New( X, Clone( P^ )) ;
- I've tried
- R := New( TypeOf(P^) , Clone( P^ )) ;
- etc. What am I forgetting ?
- }
- end ;
- end.
- -----Cut-here--------Cut-here--------Cut-here--------Cut-here-------Cut-here----
-
- Grace & peace, pete
- - - - - - - - - - - - - - - - - - - - - - - - - - -
- Peter N Roth roth@oasys.dt.navy.mil
- Do what you can with what you have where you are. - D L Moody.
-