Understand deinitialization and inheritance in swift language
Asked Answered
K

2

24

Let's say I have two classes: Base class and sub class like this:

class Base{
    var name: String?
    init() {
       name = "The base class"
    }

    deinit {
       println("call Deinitialization in base class")
       name = nil
    }
}

class Sub: Base{
    var subName: String?
    init() {
     super.init()
     subName = "The sub class"
    }

    deinit {
       println("call Deinitialization in sub class")
       subName = nil
       // does it really call super.deinit() ?
       // or assign name = nil ?
    }
}

When the deinitializer of sub class is called, does it call super.deinit() to assign nil to name variable? Or I have to assign by hand in deinitializer of subclass?

Knecht answered 3/6, 2014 at 15:56 Comment(0)
E
34

You can optionally have a deinit inside your subclass.

If you do

    let x = Sub()

you'll see that first the deinit called is the one inside Sub() then after, base deinit is called. So yes the super.deinit() is called but after the subclass.

Also the book says (page 286):

You are not allowed to call a deinitializer yourself. Superclass deinitializers are inherited by their subclasses, and the superclass deinitializer is called automatically at the end of a subclass deinitializer implementation. Superclass deinitializers are always called, even if a subclass does not provide its own deinitializer.

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l

Endometrium answered 3/6, 2014 at 16:8 Comment(0)
R
8

Superclass deinitializers are inherited by their subclasses, and the superclass deinitializer is called automatically at the end of a subclass deinitializer implementation. Superclass deinitializers are always called, even if a subclass does not provide its own deinitializer.

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l

Rawdan answered 3/6, 2014 at 16:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.