Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
Why can't I call a function over a subclass?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2007-10-05 (15:49)
From: Luca de Alfaro <luca@d...>
Subject: Re: [Caml-list] Re: Why can't I call a function over a subclass?
Yes, here is some code.  Any help would be very much appreciated.
The following fails to type check:

class p (x: int) = object
  method plus1 : int = x + 1

class p2 (x: int) = object
  inherit p x
  method plus2 : int = x + 2

class r = object (self)
  val mutable l = []
  method make_el x = new p x
  method add (x: int) : unit = l <- (self#make_el x) :: l
  method length : int = List.length l
  method total : int = List.fold_left (fun t el -> t + el#plus1) 0 l

class r2 = object
  inherit r
  method make_el x = new p2 x
  method total2 : int = List.fold_left (fun t el -> t + el#plus2) 0 l

What I am trying to do is to replace, in l, elements of type p with elements
of type p2, so that my class r2 can offer more methods (or use them
internally).  However, the compiler complains that p2 and p are not
compatible, because p does not have method plus2 (in spite of the fact that
no runtime error can occur).

I am not a deep expert of Ocaml type system for classes, as you might have
guessed by now, so if someone were able to suggest a set of type
casts/notations/... that would make the above go through, I would be very
In my real (large) code, I use the elements of the list l in many places
inside the code of r (and by inheritance, r2).

Do you have any code that we can look at to see what the problem is?  Can
> you perhaps construct a small yet complete example that demonstartes the
> issue?
> --
> William D. Neumann