+1 vote

does GDScript support virtual functions?

in Engine by (271 points)

1 Answer

+2 votes

You can make a base class and then have a derived class extend from it like so:

extends "res://path/to/base.gd"

Then in your derived class you can call the base class's functions by preceding the call with . like so (equivalent to Java's super or C#'s base):

._my_func()

So if both the derived and base class have a myfunc(), you can put code in both. If you want the derived class to call the base function you can, or you can override it by just not calling the base function.

You can also just put pass in the base function if you want it to be "pure" virtual (though it's not really pure virtual as GDScript does not enforce that it be implemented anywhere). In fact, GDScript doesn't really enforce anything, so you can mess around with different parameters and stuff too, it's up to the programmer to keep track of things.

by (101 points)
edited by

I think the _ is convention for a private or protected method or member.

Exactly. This is the same in Python and sometimes in Javascript.

Ah, thanks guys I will update that.

Yes, it's a good example of virtual functions, but I still have a question.
Is it possible to call derived class function from the base class? Consider this example:
Base class:

func DoWork():
    return Worker()
func Worker():
    pass

Derived class:

func Worker():
    # some code here

Can I make the call to the reference of the base class, which is instantiated as derived class, call DoWork operation and make derived class do it's work?
Basically I'm asking about pure virtual functions as in other languages.

@Ternvein, yes that will work as you expect.

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 webmaster@godotengine.org with your username.