GDScrpt OOP problem (inheritance)

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

I would like to have parent class using a method that’s declared in child class.

Forexample:

extends "res://BaseMap.gd"
    
func mapfunction(arg):
  if arg == "bossfight":
    startbossmusic(arg)
  if arg == "regularfight":
    startmusic(arg)
  pass

BaseMap.gd script would be like this:

extends Node

func fight():
  if(value == "bossfight"):
    mapfunction(value)

Is there a way to use the method mapfunction in the parent class? Because this worked fine in 2.1 (and even 3.0, but not in 3.1…)

I would like to let a base map class that handles some logic… tells to the child class which one it should be.

:bust_in_silhouette: Reply From: Zylann

I think it does not work in 3.1 because you are actually breaking OOP here. You use a function in a class where it is not defined, and not defined either in any of its bases. The fact it worked before was actually not wanted so likely a bug/flaw.

What you can do to make it work (and also make things more clear) is to declare that function:

func fight():
    pass # Implemented in child classes

Or call it using dynamic introspection:

call("fight")

Or use assert(false) in function’s body so base class stays abstract and to enforce implementation in derived classes.

BTW i think OP was talking about mapfunction().

hilfazer | 2018-08-21 14:51

Yes, I do mean mapfunction(). It’s the function that’s defined in child class and called in parent class. Because every child node has its own version of “mapfunction()”.

Qws | 2018-08-21 16:11

Kinda wish it did work, even though it was not intended, because GDsript’s dynamic nature.

Qws | 2018-08-21 16:15