Supertype method call inside subtype method with same name

I defined some struct that is the subtype of Parent.
There is a method I’d like to change for the Child type but at the same time I want it to call
the same method for Parent type.
What is the correct way to get this behaviour?

abstract type Parent end

mutable struct Child <: Parent
    height
end

get_height(x::Parent) = x.height/100
function get_height(x::Child)
    get_height(convert(Parent,x)) + 0.01
end

a = Child(180)
get_height(a) # should return 1.81

When I launch this code I get the following error:

StackOverflowError:

Stacktrace:
 [1] get_height(::Child) at ./In[18]:9 (repeats 79984 times)

I don’t want to change the name of my method, because there are many Children subtypes with similar methods

Child is already a subtype of Parent, so your convert call doesn’t change anything. Furthermore, Parent is an abstract type and so cannot be instantiated, i.e. no values can directly have type Parent, though they can be of its concrete subtypes.

You can use invoke to call the more generic method. Alternatively, you can also lean further into multiple dispatch:

_get_height(x::Parent) = x.height / 100

get_height(x::Parent) = _get_height(x)

get_height(x::Child) = _get_height(x) + 0.01
3 Likes

Interesting, thanks