English version
Accueil     À propos     Téléchargement     Ressources     Contactez-nous    

Ce site est rarement mis à jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml à l'adresse ocaml.org.

Browse thread
[Caml-list] Passing self to a new object
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2001-10-29 (09:03)
From: Jacques Garrigue <garrigue@k...>
Subject: Re: [Caml-list] Passing self to a new object
From: Andrew Lawson <andrew@absentis.com>

> 	I'm writing a gui program where the callback for a button
> creates a new object (also a gui) and needs to pass it a reference to
> itself in order that the new object can contact the original for
> information. The classes look something like this;
> class xyz = 
> 	let top = ... in
> 	let ... = ... in
> 	object (self)
> 	  method btnNew  = ... ~command:(fun () = new abc self) top in
> 	...
> 	...
> 	end
> and abc (parent:xyz) =
> 	object (self)
> 	var myparent = parent
> 	...
> 	end
>My error is;
> .....
> Self type cannot escape its class

You've bumped into a painful quirk of ocaml's object system: self's
type is not xyz, and must be handled with care.

(By the way, your program seemed strange, since you were using self
and abc before defining them, but I suppose it was a copy error, and I
corrected it.)

The general solution to this is to first define a class type:
  class type xyz_t = object ('self)
       btnNew : ...

Then change the code in btnNew to
  new abc (self :> xyz_t)

Remark that making xyz_t exact may be a bit lengthy, but you may leave
out methods you don't need to call from abc.

Hope this helps,

Jacques Garrigue
Bug reports: http://caml.inria.fr/bin/caml-bugs  FAQ: http://caml.inria.fr/FAQ/
To unsubscribe, mail caml-list-request@inria.fr  Archives: http://caml.inria.fr