Files
mist-website/content/docs/guide/classes.mdx
T
2026-07-03 21:55:16 +02:00

92 lines
1.7 KiB
Plaintext

---
title: Classes
description: Class declarations, constructors, inheritance, virtual dispatch, and the override keyword.
icon: Shapes
---
Mist introduces `class` as syntactic sugar for a Rust struct with a virtual method table (vtable).
```mist
pub class Animal
{
str& name;
pub constructor(str& name)
{
self.name = name;
}
pub void speak(&self)
{
println!("...");
}
}
```
Class fields can have default initializers:
```mist
class Player
{
i32 health = 100;
str& name;
}
```
### Inheritance
```mist
class Dog : Animal
{
pub constructor(str& name)
{
super = Super::new(name);
}
void speak(&self) override
{
println!("Woof!");
}
}
```
The `override` keyword supports explicit base class targeting (Required if overriding a nested parent):
```mist
void speak(&self) override(Animal)
{
println!("Woof!");
}
```
### Implementations
You can implement directly on the class body:
```mist
class Circle
{
constructor() {}
impl std::fmt::Display
{
Result<(), std::fmt::Error> fmt(&self, Formatter<'_> f)
{
write!(f, "●")
}
}
}
```
### Under the Hood
A class `Dog : Animal` generates:
1. A Rust struct with a `_super: Animal` field (or `_vptr: &'static [*const c_void]` for root classes)
2. A vtable constant with function pointers for each public method
3. An `impl` block with `Deref<Target = Animal>` and `DerefMut`
4. Method trampolines (`__m_<name>`) that are dispatched through the vtable
5. A `new()` constructor that initializes via `MaybeUninit` and calls the user's `constructor(&mut self)`
The vtable is unified: parent entries are copied, overridden entries replace parent slots, and new methods are appended.