base() question :-)

  • Thread starter Thread starter Simon
  • Start date Start date
S

Simon

Hi everyone,

Quick question:

If I don't use base() in a subclass's construcor, will the base classes
constructor be called at any point. It's just, I would have thought that the
base class constructor would always need to be called before anything else
seeing as the subclass may well depend on functionality and variables
created in the base class.

When base() is used, does it get called before anything else or is there a
way to control when it gets called.

Simon
 
If you don't call it expcitly, it will never be called. If you do want it
called, it will be called prior to any other code in the subclass's
constructor.
 
That is not correct.
The base class constructor is always called.
If you do not explicitly specify which one,
the default constructor is called.
The default constructor is the one which do not have parameters.
So, we can verify this by not providing a default constructor for a test
base class:
class Base
{
public Base( int id ) {}
}
class Concrete : Base
{
public Concrete() {}
}

This will result in compilation error:
"No overload for method Base takes 0 arguments"
However, if we remove the parameter from Base constructor,
the code will compile.
 
Marina said:
If you don't call it expcitly, it will never be called.

From the C# spec, section 17.10.1:

<quote>
If an instance constructor has no constructor initializer, a
constructor initializer of the form base() is implicitly provided.
</quote>
 
Marina said:
If you don't call it expcitly, it will never be called. If you do want it
called, it will be called prior to any other code in the subclass's
constructor.
Howdy, I just thought I would jump in here too with my two cents. :>

The advantage of this is with constructor chaining (I'm sure there are more
reasons, but this is one I like to use it for :>). In other words, you're
overloading constructors, gotta love OOP! :>

Take a look here for Chaining.
http://www.c-sharpcorner.com/Language/ConsNDestructorsInCSRVS.asp
 
Hi everyone,

If the base constructor is implicitly called whether you specify it or not,
then what is the point of base()?

Thanks for your help so far everyone. Much appreciated

tce
 
Simon said:
If the base constructor is implicitly called whether you specify it or not,
then what is the point of base()?

Only clarity - just specifying it (without any parameters) is basically
redundant.
 
Because sometimes you want to call a base constructor that has variables in
it.
For example:

public class Point
{
public int X;
public int Y;

public Point(int xValue, int yValue)
{
X = xValue;
Y = yValue;
}
}

public class ExtendedPoint : Point
{
public ExtendedPoint(int xValue, int yValue) : base(xValue, yValue)
{
}
}
 
Back
Top