How to add a GDScript constructor to a C++ class?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By sheepandshepherd
:warning: Old Version Published before Godot 3 was released.

I made a C++ class that’s usable from GDScript. I want to change the new() constructor/initializer to one with 3 arguments. This can be done in GDScript classes by overriding the _init function, but binding _init for a C++ class doesn’t seem to do anything:

# works
var a = RangeIterator.new()

# error: "Invalid call to function 'new' in base 'GDNativeClass'. Expected 0 arguments."
var b = RangeIterator.new(0, 10, 2)

And the C++ constructors aren’t usable from GDScript.
Is there any other way to change new() for a C++ class?

:bust_in_silhouette: Reply From: Ryan Brent Taylor

I don’t know if this is possible, however I have an alternative you may want to consider. Look into the factory pattern.

Rather than overriding the C++ constructor in gdscript, create a different method that returns an object in the state you want. For example:

# MyObject has a constructor that takes three arguments.
# Rather than overriding _init, provide a new method that is
# for all intents and purposes, static that returns a "MyObject"
# instance in the state you want.
func alternate_init(a):
    return MyObject.new(1, a, 2)

GDScript actually has static functions, so a static factory is a good way for script classes. But static functions are not bindable from C++, AFAIK, since only methods can be bound.

A self-returning setter method is good enough for testing (this isn’t really meant to be used from GDScript anyway):
for i in RangeIterator.new().set_range(0, 10, 2):
print(i)

sheepandshepherd | 2016-02-23 16:55