- Courses
- đ»Programming Languages
- đ«OCaml (WIP)
- Object-Oriented Programming
- Classes, Objects and Methods
On this page
OCaml Classes, Objects & Methods: Structural System
Published on September 19, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
OCaml's object system is structural: an object's type is determined entirely by the methods it provides, not by the class that created it. This means any object with the required methods can be used where a particular object type is expected, regardless of its class hierarchy. Classes serve as convenient templates for creating objects, but they are not the source of type identity. This article explains how classes, objects, methods, and instance variables work, how the # operator invokes methods, how self refers to the current object, and how coercions enable width subtyping. It also covers immediate objects, the Oo module, and the practical pitfalls that arise from structural typing.
What Makes OCaml's Object System Structuralâ
In languages with nominal typing such as Java or C++, an object's type is tied to its class. A Button is a Widget only because Button explicitly inherits from Widget. In OCaml, subtyping is structural. An object type is a set of method names and their types. Any object that provides those methods is a subtype of that object type, whether or not it shares any class ancestry.
class stack_of_ints = object
val mutable items = ([] : int list)
method push x = items <- x :: items
method pop =
match items with
| [] -> failwith "Empty"
| x :: rest -> items <- rest; x
method peek =
match items with
| [] -> failwith "Empty"
| x :: _ -> x
method size = List.length items
end
The class stack_of_ints defines a mutable instance variable items and four methods. Its type is inferred as:
< peek : int; pop : int; push : int -> unit; size : int >
This type is purely structural. It lists the public methods and their types. The instance variable items is hidden. Private methods, if any, would also be hidden. The type says nothing about the class name. Any object with exactly these four methods would be accepted wherever this type is expected.
This structural nature has a direct consequence: a function that only uses some of an object's methods will have a narrower inferred type than the object's full type. For example, a function that only calls pop and size will be inferred as accepting any object with those two methods, even if that object has nothing else in common with a stack.
Defining a Class and Creating Objectsâ
A class definition uses the class keyword followed by the class name and an object ... end body. The body contains val declarations for instance variables and method declarations for methods.
class point x_init =
object
val mutable x = x_init
method get_x = x
method move d = x <- x + d
end
The class point takes a single argument x_init. Each time an object is created from this class, the argument is evaluated and the instance variable x is initialized to that value. The mutable keyword on val makes the instance variable assignable. The <- operator updates a mutable instance variable, using the same assignment operator used for mutable record fields.
Creating an object uses the new keyword:
let p = new point 5
The expression new point 5 creates an object of type point. The inferred type of p is point, which expands to < get_x : int; move : int -> unit >. The class name serves as a convenient abbreviation for the object type.
Instance Variables and Mutable Stateâ
Instance variables are declared with val. They are immutable by default. Adding mutable permits assignment with <-.
class counter =
object
val mutable count = 0
method get = count
method incr = count <- count + 1
method reset = count <- 0
end
Every object created from counter has its own count variable. The mutable keyword is required because incr and reset assign to count. Without it, the compiler would reject the assignment.
Instance variables are private to the object. They cannot be accessed from outside the class. The only way to observe or change them is through methods. This encapsulation is enforced by the type system: the object's type lists methods, not instance variables.
Methods and the # Operatorâ
Method invocation uses the # operator:
let c = new counter
let () = c#incr
let n = c#get
The expression c#incr invokes the incr method on the object c. Methods are functions, so c#incr has type unit -> unit when partially applied? Actually, c#incr with no arguments invokes the method and returns unit. If a method takes arguments, such as method move d = ..., then p#move is a function of type int -> unit, and p#move 3 invokes it with argument 3.
A method with no arguments is not a value; it is a method that is evaluated on each invocation. This distinction matters when the method body has side effects or reads mutable state. Each call to c#get reads the current value of count.
Reference to Selfâ
Methods often need to refer to the object on which they are invoked, either to call other methods or to pass the object to a function. The self pattern in the object binding provides this reference.
class counter =
object (self)
val mutable count = 0
method get = count
method incr = count <- count + 1
method reset = count <- 0
method print_twice =
print_int self#get;
print_int self#get
end
The (self) after object binds the name self to the current object. Inside methods, self#get calls the get method of the same object. This is useful when a method's behavior depends on other methods that subclasses might override. Without self, a method that wants to call another method would have no way to do so.
The self reference has the type of the object being defined, which is a recursive type. The compiler infers it automatically; no explicit annotation is required.
Parameterized Classesâ
Classes can be parameterized by type, making them polymorphic over the types of their instance variables and methods.
class ['a] stack =
object
val mutable items = ([] : 'a list)
method push x = items <- x :: items
method pop =
match items with
| [] -> None
| x :: rest -> items <- rest; Some x
method peek =
match items with
| [] -> None
| x :: _ -> Some x
end
The ['a] after class declares a type parameter. The instance variable items is annotated with 'a list so that the compiler knows the element type. Without the annotation, [] would be inferred as 'a list, but the class would not be polymorphic unless the parameter was declared.
Parameterized classes are instantiated with a concrete type inferred from usage:
let s = new stack
let () = s#push 3
At this point, s has type int stack. The type parameter is fixed to int by the first use of push. Attempting to push a string afterward produces a type error.
Immediate Objects and Object Typesâ
Objects can be created without a class using an immediate object expression.
let o =
object
val mutable n = 0
method incr = n <- n + 1
method get = n
end
The type of o is inferred as < get : int; incr : unit >. No class name is involved. Immediate objects are useful when a class definition would be unnecessary overhead, such as creating a one-off object to pass to a function.
Object types can also be written explicitly and used in type annotations, just like record types. The type < get : int; incr : unit > is a valid type expression. Unlike records, object types do not need to be predefined; they are structural and can be written inline.
Coercion and Width Subtypingâ
Because object types are structural, an object with more methods can be coerced to an object type with fewer methods. This is called width subtyping.
class colored_point x_init c =
object
inherit point x_init
val color = c
method color = color
end
let cp = new colored_point 5 "red"
let p : point = (cp :> point)
The object cp has methods get_x, move, and color. The type point requires only get_x and move. The coercion (cp :> point) hides the color method, producing an object of type point. This is safe because every colored_point provides all the methods that point requires.
Coercion in the opposite direction, from point to colored_point, is not allowed. A point might not have a color method, so the coercion would be unsafe. OCaml rejects it at compile time.
The coercion operator :> can also be used in function arguments and in module signatures. It is the mechanism that makes heterogeneous collections of objects possible: a list of point values can contain objects that were originally created from subclasses, as long as each is coerced to point before being inserted.
The Oo Moduleâ
The Oo module provides a small set of operations on objects that cannot be expressed through methods alone.
Oo.copycreates a shallow copy of an object. The copy has the same instance variables and methods, but it is physically distinct from the original.Oo.idreturns a unique integer identifier for an object. The identifier is unique across all objects in the program.- Physical equality
==and inequality!=compare object identity. Two objects with the same method results are not physically equal unless they are the same object. - Structural equality
=and<>compare objects by their current state. For mutable objects, this comparison can be surprising because it depends on the values of instance variables at the moment of comparison.
The Oo module is rarely needed in everyday code, but it is useful for debugging, identity checks, and implementing object-based data structures that need to distinguish objects by identity rather than by state.
Common Pitfalls and How to Avoid Themâ
The first pitfall is assuming that a subclass is automatically a subtype. It is not. OCaml requires an explicit coercion to convert an object of a subclass to the type of its superclass. Without the coercion, the compiler infers the narrower type and rejects the assignment.
let p : point = new colored_point 5 "red"
(* Error: This expression has type colored_point
but an expression was expected of type point *)
The fix is to add the coercion: (new colored_point 5 "red" :> point).
The second pitfall is the accidental structural match. A function inferred to accept any object with certain methods will accept unrelated objects that happen to have those methods. This is sometimes convenient, but it can lead to confusing type errors when the inferred type is more general than intended. Annotating the parameter with a class type or an object type narrows the type and produces clearer errors.
The third pitfall is forgetting that object types are closed. An object type < get : int; incr : unit > requires exactly those methods, no more and no fewer. If a function is annotated to accept that type, it will reject objects that have additional methods unless they are coerced first. This is the opposite of the open row polymorphism used by polymorphic variants.
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.
Key Takeawaysâ
OCaml's object system is structural: object types are determined by method names and signatures, not by class names. Classes define templates for objects, using val for instance variables and method for methods. Mutable instance variables use mutable and the <- assignment operator. The # operator invokes methods. The self reference allows methods to call other methods on the same object. Parameterized classes support polymorphic objects. Immediate objects provide objects without classes. Coercion with :> enables width subtyping, allowing objects with more methods to be used where fewer methods are required. The Oo module provides identity and copying operations. Understanding structural typing is essential for predicting when objects are compatible and when explicit coercions are needed.
Frequently Asked Questionsâ
What is a structural object system?
A structural object system determines an object's type by the methods it provides, not by the class that created it. Any object with the required methods is a subtype of that object type, regardless of class ancestry. OCaml uses structural typing for objects.
How do you create an object in OCaml?
Define a class with the class keyword and an object ... end body, then instantiate it with the new keyword. Alternatively, create an immediate object using an object expression without a class.
What does the # operator do in OCaml?
The # operator invokes a method on an object. For example, p#get_x calls the get_x method on the object p. It is the OCaml equivalent of the dot operator in imperative object-oriented languages.
What is self in an OCaml class?
self is a reference to the current object. It is bound by writing object (self) in the class body. It allows methods to call other methods on the same object or to pass the object to functions.
What is the difference between a class and an object type in OCaml?
A class is a template that defines instance variables and methods and serves as a function for creating objects. An object type is a structural type that lists the public methods an object provides. A class name is an abbreviation for an object type.
Can you coerce a superclass object to a subclass type in OCaml?
No. Coercing from a superclass type to a subclass type is unsafe and rejected by the compiler. The superclass object might not actually be an instance of the subclass. Only width subtyping coercions, from a subtype with more methods to a supertype with fewer methods, are allowed.
What is the Oo module used for?
The Oo module provides functions for copying objects (Oo.copy) and obtaining unique object identifiers (Oo.id). It also documents the physical equality operators == and != for comparing objects by identity.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Object-Oriented Programming
Next
Inheritance and Structural Subtyping
- What Makes OCaml's Object System Structural
- Defining a Class and Creating Objects
- Instance Variables and Mutable State
- Methods and the
#Operator - Reference to Self
- Parameterized Classes
- Immediate Objects and Object Types
- Coercion and Width Subtyping
- The
OoModule - Common Pitfalls and How to Avoid Them
- Key Takeaways
- Frequently Asked Questions
