# Generate a (mutable) struct which inherits others

**URL:** <https://discourse.julialang.org/t/generate-a-mutable-struct-which-inherits-others/47347>\
**Category:** New to Julia\
**Tags:** inheritance, struct\
**Created:** [September 27, 2020, 2:59am UTC](https://discourse.julialang.org/t/generate-a-mutable-struct-which-inherits-others/47347 "2020-09-27T02:59:15Z")\
**Posts on this page:** 1\
**Showing post:** 5

<div class="post-metadata">

**Author:** ![xiaodai](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/xiaodai/32/15937_2.png) [@xiaodai](https://discourse.julialang.org/u/xiaodai)\
**Post date:** [September 27, 2020, 3:43am UTC](https://discourse.julialang.org/t/generate-a-mutable-struct-which-inherits-others/47347/5 "2020-09-27T03:43:58Z")

</div>

Follow this example and just work thru it

```julia
mutable struct Parent
    foo
    bar
end

mutable struct Child
    parent::Parent
    foo # this is duplicated with parent
    notbar
end

parent = Parent(1, 2)

child = Child(parent, 3, 4)

child.bar # doesn't work

function Base.getproperty(child::Child, prop::Symbol)
    if prop in fieldnames(Parent) && !(prop in fieldnames(Child))
        return getfield(child.parent, prop)
    else
        return getfield(child, prop)
    end
end

child.bar # works now

child.foo # returns child value instead of parent value;

child.parent.foo # return parent's foo

```

This shows the underlying mechanism. If you do this pattern alot you can make it easier by using a macro to write those codes for you.

---

_[View the full topic](https://discourse.julialang.org/t/generate-a-mutable-struct-which-inherits-others/47347)._
