Base class constructor with parameters

This is a very common concept and often asked in object oriented interviews:

Q. A base class has a constructor with one parameter. Can the derive class still have its own additional constructor with different signature? How will you implement this in C# in order to have your code build successfully?

A. All derived classes must call the base class constructor with the correct parameter. The derived class constructor doesn’t need to match the  base class constructor signature but it MUST class the base class constructor with the correct parameter and base class constructor must be called with all derived class constructors. You would code as following:

public [ClassName] ( [datatype] [variable] ) : base ( [variable] ) { }

Note the use of the keyword ‘base‘.

So you could may as well a derived class with no parameter which is different to base class constructor in this case(with one parameter), as long as you make call to :base() and pass the correct base class constructor parameter, you are okay.

However, you can very well have the derived class defined another set of constructors with different parameters as long as it always calls : base() and passes the correct parameter to the base class constructor. This call to base constructor must be made with all derived class constructor.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s