Can we override constructor

  • Thread starter Thread starter ad
  • Start date Start date
A

ad

When a class (say class1) inherited form another class (Class0).

The constructor in the class0 will be executing before the constructor of
class1.

Can we over the constructor?
 
Depends on what kind of constructor it is - if it is the default constructor
(i.e. constructor with no parameters) then you can't override the parent's
constructor, it will always execute. If it is a non-default constructor then
it is automatically overriden unless you call it using the "base" keyword.
Note that the default constructor of the parent is always called regardless
of what kind of constructor is being invoked of the child class. Also,
whenever a base-class constructor executes, it does so before the inherited
class constructor is run.
Hope that helps,
~amit
 
Amit said:
Note that the default constructor of the parent is always called regardless
of what kind of constructor is being invoked of the child class.

No, this is not true. You can specify which base constructor will be
called -

public ThisType(t1 p1, t2 p2): base(p1) { /*...*/ }
 
oops you're right... the default constructor of the parent class is always
called IF no other constructor is specified.
 
Amit said:
oops you're right... the default constructor of the parent class is always
called IF no other constructor is specified.

Yes, this is better. A base constructor will always be called, for
every class that descends from object, because every class must have
at least one constructor that calls a base() constructor (explicitly
or implicitly) and every call to a this() constructor must ultimately
call a base() constructor.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top