0 votes

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

Godot version 3.4.3
in Engine by (15 points)

2 Answers

+1 vote
Best answer

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

MyResource::_register_methods 
{
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. 

 resource.AddGold(otherresource)
by (284 points)
selected by
0 votes

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.

by (29,090 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.