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?
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) {
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With