virtual Functions

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

does GDScript support virtual functions?

:bust_in_silhouette: Reply From: Rodeo

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

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

indicainkwell | 2016-12-20 02:35

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

David Saltares | 2016-12-20 08:34

Ah, thanks guys I will update that.

Rodeo | 2016-12-21 16:42

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 | 2019-05-16 10:31

@Ternvein, yes that will work as you expect.

indicainkwell | 2019-10-30 02:33