Operator overloading in C++ module

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

I am trying to to implement in C++ basic math operators (+, *, +=, …) for a custom class used to handle specific data about my game.

I already managed to create that custom class in the modules folder, and bind a few basic methods. This custom class is accessible in the engine after recompiling it, and the binded methods as well. However, I found no documentation on operators overloading for the godot engine, nor found any example online.

Is it possible? And if so, is there an exemple somewhere?
If not, I guess I could add my custom class directly in the /core folder?

Here is what I have tried
MyResource.h :

class MyResource : public Reference {
   GDCLASS(MyResource, Reference);
public :
    float gold;
    void operator+=(const MyResource &obj);

void MyResource::operator+=(const MyResource &obj) {
    this->gold += obj.gold;

It compiles fine, but when I try to use the operator “+=” in the editor, I get the following error : “Invalid operands ‘Object’ and ‘Object’ in operator ‘+’”.

I have not used “ClassDB::bind_method” for the += operator. Should I?

Thank you in advance for your help

:bust_in_silhouette: Reply From: Zylann

Operator overloading is not supported by Godot’s scripting API. It will only work in your C++ library, but not in GDScript or any other language using your class through Godot.

:bust_in_silhouette: Reply From: r.bailey

Sadly operator overloading doesn’t work in gdscript, but you can just create a method that does that and register it and just call that method with the parameters in your code.
For instance,
In your cpp code

register_method("AddGold", &MyResource::AddGold);

MyResource::AddGold(MyResouce &obj) 
this.gold += obj.gold; 

Then in the engine .gd class wherever you have this object build.