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?
2 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) {
}
}
2 Comments
Miria
Not sure I get it. In the first example, there is Child(int x): base(x) so I guess both will be called?
Jon
@Miria: Yes. There is no way that some base constructor will not be called (e.g. in the second example the compiler will not let you remove
base(x)); using base just allows you to choose which one will be called, and with what parameters.