Can a class have a constructor?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By patatra

Hye everyone,
Can a class created in a class_name have a constructor?

Good Day,

:bust_in_silhouette: Reply From: cm

Yes, you can override _init.

See Class constructor in the docs

It’s work, thank you

Good Day,

patatra | 2022-05-14 08:36

You can use the named constructor pattern. E.g.

class_name MyClass extends Node

var parameter: int

static func create(new_params: int) -> MyClass:
	var instance = MyClass.new()
	instance.parameters = params
	return instance

Then create your instances like MyClass.create(...) instead of MyClass.new().

Why do you reply to a question 2 years later, with a solution that isn’t wrong but just unnecessary? (You can override _init() with parameters already, no need for your own create() method.)

Because searching for constructors in Godot I ended up here. I didn’t like the solution becase it is not really a contructor and I shared an alternative solution in case it is usefull for others.

When using _init signature hinting is just on-editor validated and it just suggests the number or arguments. Also it lacks semantic.

I believe that named constructor is a more robust approach.

IMHO it’s not a more robust method because now you have two methods to create the object, which makes it more prone for bugs.