A tutorial about parametric constructors in Julia (1/2)

submited by
Style Pass
2024-09-30 18:30:05

Julia enables the definition of parametric types, similar to class templates in C++. They let the user define a “template” for a struct where the types are only defined in general terms, and the user will “fill” the definitions once they create an actual object. To build a struct, one can implement constructors, which are special functions whose name is the same as the struct (again, similar to C++) and whose purpose is to set up the object so that its state is consistent.

Constructors for parametric types can be complex. Still, it is crucial to understand how they work, as they make the code more robust (you can spot conceptual errors earlier) and more performant (the code runs faster).

I wrote this long blog post to put together some facts that I have discovered about this topic. I often find myself re-reading the chapters in the Julia Manual about types and methods, trying to figure out why the way I defined a constructor is not working or doing what I was expecting. I will stick to facts as much as possible, providing as many practical examples as needed, but please remember that I am not an expert in this field, and some of my explanations may be incorrect. Send me an email if you think something is wrong or missing.

This defines a type Point that contains two fields: x and y. Thus, Point can represent a 2D point on the Cartesian plane. If one wants to define the same in C++, one could come out with the following definition:

Leave a Comment