Files

109 lines
2.0 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;
}
```
### Virtual Methods
The `virtual` keyword marks methods as dispatchable through the vtable, enabling polymorphic behavior:
```mist
pub class Animal
{
str& name;
pub constructor(str& name)
{
self.name = name;
}
pub virtual void speak(&self)
{
println!("...");
}
}
```
When a method is marked `virtual`, it can be overridden in subclasses and will be dispatched dynamically at runtime through the vtable. Non-virtual methods are called statically.
### 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!");
}
```
Methods marked `override` are automatically virtual if the parent method is virtual. The semantic analyzer validates that overridden methods match the parent's signature.
### 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, "●")
}
}
}
```
---
For details on how classes are compiled — vtable layout, constructor codegen, and safety verification — see [Class Internals](/docs/internals/classes).