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

2 Likes

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().

6 Likes

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.)

1 Like

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.

2 Likes

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.

1 Like

It is not a matter of discussion, Named Constructors/Factory Methods is a well known design pattern.

If it fits your needs, you use it.

As I said, it is also a matter of semantic. In your projects reality it may happen instantiating an object is not the same as “creating” it.

If you have some kind of persistence, it is not the same creating an object with default values, than recovering them form a resource. For instance.

Create method in this case acts as boilerplate state generator.

3 Likes

Yes! This is a great design pattern actually.

This is what Josh Bloch calls the “static factory method” (author of Effective Java) and what some others might call a static “creation” method

It’s a great pattern for when you want disambiguate multiple constructors which also avoids using confusing overloaded methods or adding parameters that don’t belong and extra logic into your main constructor.

This is actually what I was looking for. Thank you :pray:

1 Like