Returning an extended class spawns error

Godot Version

4.2.1.stable

Question

I have 4 weapon classes that extend the basic Weapon class, but when I do something like the example below, I’m getting an error. I haven’t hard coded much in the last few years, but this is usually valid… Pointers, please?

func get_default_weapon() -> Weapon:
	return WeaponBow

Here we have the base class Weapon and also WeaponBow which extends Weapon. But I’m getting:

Parser Error: Cannot return value of type “WeaponBow” because the function return type is “Weapon”.

Do I have to work around this or am I missing something? Halp, please.

Just to note that using Variant as a return type solves the above. It’s working fine that way, but shouldn’t using the base class Weapon work too? I think so.

func get_default_weapon() -> Variant:
	return WeaponBow

Or maybe it’s me misunderstanding something vital here.

If your WeaponBow class extends Weapons, then yes.

Weapon.gd:

extends Node
class_name Weapon

WeaponBow.gd:

extends Weapon
class_name WeaponBow

Then doing this works for me without errors:

func get_default_weapon() -> Weapon:
	return WeaponBow

Hmm, not sur what to tell you…

FWIW, in my project that method is used in a different class (each toon has its own weapon, thus the method). Still, when written like below, the problem remains.

I’m guessing you’re also on 4.2.1.stable? Is there some setting I might have tripped? :face_with_raised_eyebrow:

headdesk

You can’t just spew a class name as a return value. But, if I use a variable of type WeaponBow, it will work. As it should.

I’m an idiot.

Sorry.

1 Like