On this page

OCaml Inheritance & Structural Subtyping

Published on September 19, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

Inheritance and subtyping are separate concepts in OCaml. Inheritance is a syntactic mechanism that lets one class reuse and override the definitions of another. Subtyping is a semantic relation between types: an object type with more methods is a subtype of one with fewer methods, regardless of how either class was defined. Understanding this separation is essential for predicting when an object of one class can be used where another type is expected, and when an explicit coercion is required.

The Core Distinction: Inheritance vs. Subtyping​

In mainstream object-oriented languages such as Java and C++, inheritance and subtyping are tightly coupled. A class that extends another class is automatically a subtype of it, and the compiler treats a reference to the subclass as compatible with a reference to the superclass without any explicit conversion.

OCaml deliberately breaks this coupling. Inheritance is a relation between classes, used for code reuse. Subtyping is a relation between types, used for compatibility. The two can coincide, but they do not have to.

The OCaml manual states this directly: "Be aware that subtyping and inheritance are not related. Inheritance is a syntactic relation between classes while subtyping is a semantic relation between types." A class can inherit from another class without its object type being a subtype of the parent's object type, and a class can produce objects that are subtypes of a type without inheriting from any class that defines that type.

This separation has practical consequences. When a subclass object is used where a superclass type is expected, OCaml does not insert an implicit coercion. The programmer must write an explicit coercion using the :> operator. This explicitness makes the type system predictable and prevents the silent, sometimes surprising, subtype conversions that occur in languages with nominal subtyping.

Inheritance in OCaml​

Inheritance allows a class to reuse the instance variables and methods of another class. The inherit keyword brings the parent class's definitions into the child class.


class point x_init =

  object

    val mutable x = x_init

    method get_x = x

    method move d = x <- x + d

  end



class colored_point x_init c =

  object

    inherit point x_init

    val color = c

    method get_color = color

  end

The colored_point class inherits from point. It has all the methods of point—get_x and move—plus its own method get_color and its own instance variable color. The inherited instance variable x is also present, initialized by passing x_init to the parent's initialization.

Overriding Methods​

A child class can override a method from its parent by defining a method with the same name.


class counted_point x_init =

  object

    inherit point x_init as super

    val mutable count = 0

    method get_x =

      count <- count + 1;

      super#get_x

  end

The as super binding gives a name to the parent class, allowing the child to call the parent's implementation of a method. In this example, counted_point overrides get_x to increment a counter before delegating to the parent's get_x via super#get_x. Without the as super binding, the child would have no way to access the overridden implementation.

Multiple Inheritance​

OCaml allows a class to inherit from more than one parent class.


class printable_point y =

  object

    inherit point y

    method print = string_of_int self#get_x

  end



class printable_colored_point y c =

  object

    inherit printable_point y

    inherit colored_point y c

  end

When two parent classes define a method with the same name, the last one inherited wins. The compiler may issue a warning about the conflict, which can be suppressed if the override is intentional.

Multiple inheritance is a tool for mixing in behavior rather than a mechanism for resolving conflicting interfaces. Because object types are structural, the resulting class produces objects with the union of all inherited methods.

Initializers​

A class can contain an initializer block that runs when an object is created. Initializers from parent classes run in the order the classes are inherited.


class account =

  object (self)

    val mutable balance = 0

    initializer

      print_endline "account created"

    method deposit amount = balance <- balance + amount

    method get_balance = balance

  end

The initializer block is executed after the instance variables are initialized and before the object is returned by new. It is useful for setting up invariants or registering objects in a global collection.

Structural Subtyping in OCaml​

OCaml uses structural subtyping for objects. An object's type is determined entirely by the methods it provides, not by the class that created it. The type < get_x : int; move : int -> unit > describes any object with those two methods, regardless of its class ancestry.

Consider two classes that are completely unrelated but happen to define the same methods.


class point_a =

  object

    method get_x = 5

    method move (_ : int) = ()

  end



class point_b =

  object

    method get_x = 10

    method move (_ : int) = ()

  end

Both classes produce objects of type < get_x : int; move : int -> unit >. A function that accepts this type will accept objects from either class.


let distance (p : < get_x : int; move : int -> unit >) = p#get_x

The function distance does not care whether its argument came from point_a or point_b. It only cares that the argument provides a get_x method returning an integer.

Width Subtyping​

An object with more methods can be used where an object type with fewer methods is expected. This is called width subtyping.


class colored_point x_init c =

  object

    inherit point x_init

    method get_color = c

  end



let cp = new colored_point 5 "red"

The object cp has methods get_x, move, and get_color. Its type is < get_color : string; get_x : int; move : int -> unit >. This type is a subtype of < get_x : int; move : int -> unit > because it provides all the required methods and more.

Width subtyping is not automatic. The programmer must explicitly coerce the object.


let p : < get_x : int; move : int -> unit > = (cp :> < get_x : int; move : int -> unit >)

The coercion operator :> takes an object with a subtype and produces an object with the supertype. The extra get_color method is hidden. The resulting object is not a different object; it is the same object viewed through a narrower type.

Coercion and the :> Operator​

The coercion operator :> has several forms.

The most general form specifies both the source and target types: (expr :> target_type). The compiler infers the source type from expr and checks that it is a subtype of target_type.

A second form specifies only the target type: (expr :> target_type). This is the most common form. The compiler infers the source type and performs the subtype check.

A third form specifies both types explicitly: (expr : source_type :> target_type). This form is useful when the source type cannot be inferred unambiguously or when the programmer wants to be explicit.

Coercion is not limited to objects. It also works for polymorphic variants and for type constructors whose parameters are covariant. For example, a square list can be coerced to a shape list because lists are immutable and covariant in their element type.


let squares : square list = [square 10; square 20]

let shapes : shape list = (squares :> shape list)

Arrays, by contrast, are invariant. A square array cannot be coerced to a shape array because that would allow storing a non-square shape into an array that is supposed to contain only squares. OCaml rejects this coercion at compile time.

Coercing self​

Coercing self to a superclass type within a class definition is a common pattern, but it has a subtle restriction. The following code is rejected by the compiler.


class c = object method m = 1 end

and d = object (self)

  inherit c

  method n = 2

  method as_c = (self :> c)

end

The error is: "Self type cannot escape its class." The type of self includes the as_c and n methods, and coercing it to the closed type c would fix the type of self to a closed object type, preventing further extension of the class.

However, the most common case—coercing self to its own class type—is detected as a special case and is allowed.


class c = object (self)

  method m = (self :> c)

end

This compiles because the compiler recognizes that the target type is the class being defined and does not close the self type prematurely. This idiom is useful for keeping a list of all objects belonging to a class or its subclasses.

How Inheritance and Subtyping Interact​

Inheritance does not imply subtyping. A class that inherits from another class may produce objects whose type is not a subtype of the parent's object type. This occurs when a method's type involves self.

Consider a class with a method that takes another object of the same type.


class point = object (self : 'self)

  method eq (other : 'self) = self = other

end



class colored_point = object

  inherit point

  method color = "red"

end

The type of point is < eq : 'a -> 'a; .. > as 'a. The type of colored_point is < color : string; eq : 'a -> 'a; .. > as 'a. The eq method in colored_point expects an argument of type colored_point, not point. Therefore, colored_point is not a subtype of point, even though it inherits from point.

This is the opposite of what happens in Java, where a subclass is always a subtype of its superclass. OCaml's structural typing makes the subtype relation depend on the full method types, including the type of self. When self appears in a method's type, inheritance does not automatically produce a subtype relation.

Conversely, a class that does not inherit from another class can produce objects that are subtypes. Any object that provides the required methods is a subtype, regardless of its class ancestry. This is the essence of structural subtyping.

Common Pitfalls​

The first pitfall is assuming that a subclass object can be used where the superclass type is expected without a coercion. OCaml requires an explicit coercion. Writing let p : point = new colored_point 5 "red" produces a type error. The fix is to write let p : point = (new colored_point 5 "red" :> point).

The second pitfall is coercing self to a superclass type within a class definition and encountering the "Self type cannot escape its class" error. The solution is to coerce to the class's own type or to use a method that returns the coerced object rather than coercing self directly.

The third pitfall is expecting inheritance to produce subtyping when methods involve self. As shown above, colored_point inheriting from point does not make colored_point a subtype of point when point has a method like eq that takes self as an argument. The programmer must understand the full method types to predict subtype relations.

The fourth pitfall is using structural equality on mutable objects. Because = compares the current state of instance variables, two objects that were equal at one moment may become unequal after either is mutated. For identity comparison, use == or Oo.id.

When Inheritance and Subtyping Are Useful​

Inheritance is useful for code reuse. When two classes share instance variables and methods, inheritance avoids duplication. It is also useful for overriding: a subclass can modify the behavior of a specific method while inheriting everything else.

Subtyping is useful for writing functions that operate on a family of object types. A function that only needs the get_x method can accept any object that provides it, regardless of the object's class. This enables heterogeneous collections: a list of point values can contain objects from colored_point and other subclasses, as long as each is coerced to point.

The combination of inheritance and subtyping supports the open implementation, fixed operations pattern. The set of operations is fixed by the superclass interface, but new implementations can be added by defining new subclasses that inherit from the superclass and override methods as needed. This is the scenario where objects outperform modules and functors, which favor the opposite tradeoff.

Key Takeaways​

Inheritance and subtyping are separate concepts in OCaml. Inheritance is a syntactic mechanism for code reuse between classes, using the inherit keyword. Subtyping is a semantic relation between types, based on the structural method sets that objects provide. An object with more methods is a subtype of an object type with fewer methods, but this relation does not follow automatically from inheritance. Explicit coercions with the :> operator are required to convert a subtype to a supertype. Coercing self within a class definition has restrictions that prevent the self type from escaping its class. Understanding these distinctions enables the programmer to use objects effectively for problems where open implementations and structural subtyping are the right tools.

Frequently Asked Questions​

Does inheritance imply subtyping in OCaml?

No. Inheritance is a syntactic relation between classes, while subtyping is a semantic relation between types. A class can inherit from another without its object type being a subtype, and a class can produce subtypes without inheriting from any class that defines the supertype.

How do you coerce an object to a supertype in OCaml?

Use the coercion operator :>. For example, (colored_point :> point) coerces a colored point to a point, hiding the extra methods. The coercion is safe because the source type provides all the methods required by the target type.

Why does OCaml require explicit coercions?

OCaml uses structural subtyping, and the compiler does not insert implicit coercions. Explicit coercions make the type system predictable and prevent silent conversions that could lead to runtime errors in languages with nominal subtyping.

What is width subtyping?

Width subtyping is the rule that an object with more methods is a subtype of an object type with fewer methods. For example, an object with methods get_x, move, and get_color is a subtype of an object type with only get_x and move.

Can you coerce a superclass object to a subclass type?

No. Coercing from a superclass type to a subclass type is unsafe because the superclass object might not actually be an instance of the subclass. OCaml only allows width subtyping coercions, from a subtype with more methods to a supertype with fewer methods.

What does 'Self type cannot escape its class' mean?

It means that coercing self to a closed object type would fix the type of self and prevent further extension of the class. The compiler detects this and rejects the coercion. The workaround is to coerce self to its own class type or to use a method that returns the coerced object.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Classes, Objects and Methods

Next

Objects vs Modules & Functors