Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructors inheritance

I have tried to understand but still not sure. If there is a constructor in the base class, the derived classes will always call it? I know they can override it (not correct term here, I know - I mean add code to their constructors) but I assume if the constructor is defined in the base class, the derived ones will always call it. Is that true?

like image 725
Miria Avatar asked Apr 03 '11 15:04

Miria


1 Answers

Yes, if there is a parameterless constructor it will always be called. If there is more than one constructor, you can choose which one to call with the base keyword:

class Parent {
    public Parent() {}
    public Parent(int x) {}
}

class Child : Parent {
    public Child(int x) : base(x) {
    }
}

If there is no parameterless constructor, you will be forced to do this:

class Parent {
    public Parent(int x) {}
}

class Child : Parent {
    // This will not compile without "base(x)"
    public Child(int x) : base(x) {
    }
}
like image 148
Jon Avatar answered Sep 30 '22 09:09

Jon