6

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 2

6

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) {
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Not sure I get it. In the first example, there is Child(int x): base(x) so I guess both will be called?
@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.
2

If there is only a parameterless constructor in the base class, the child class constructor will always call it first. On the other hand if you have other constructors defined in the base class, then the child class will have an option which base constructor to call.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.