Ensuring a base constructor is called?

  • Thread starter Thread starter Josh Valino
  • Start date Start date
J

Josh Valino

If I have a base class that has one constructor, is the only way that that
constructor will get called be by having no constructors in my derived
classes or explicitly calling base() in my derived constructors?
Illustration:

abstract class whatever
{
public whatever()
{
//code here I want to run
}
}

class derivedClass : whatever
{
public derivedClass() : base()
{
}
}

That ":base()" is necessary in this case, correct? I guess what I'm more
looking for is some mechansism that will ensure that code in my base classes
is always executed when a derived object is instantiated. I'm mostly trying
to compensate for a behavioral problem here, fearing that other developers
won't remember to put the ": base()" on their constructors. :-/

TIA,

Josh
 
On Jul 30, 5:08 pm, "Josh Valino" <no spam please> wrote:

That ":base()" is necessary in this case, correct?

No. If you don't specify either :base(...) or :this(...) then the
compiler effectively inserts :base() for you.
I guess what I'm more
looking for is some mechansism that will ensure that code in my base classes
is always executed when a derived object is instantiated. I'm mostly trying
to compensate for a behavioral problem here, fearing that other developers
won't remember to put the ": base()" on their constructors. :-/

They don't need to - the base class constructor will always be called.

Jon
 
If I have a base class that has one constructor, is the only way that that
constructor will get called be by having no constructors in my derived
classes or explicitly calling base() in my derived constructors?
Illustration:

abstract class whatever
{
  public whatever()
  {
    //code here I want to run
  }

}

class derivedClass : whatever
{
  public derivedClass() : base()
  {
  }

}

That ":base()" is necessary in this case, correct?  

No, the compiler will add a call for you.
I guess what I'm more
looking for is some mechansism that will ensure that code in my base classes
is always executed when a derived object is instantiated.  I'm mostly trying
to compensate for a behavioral problem here, fearing that other developers
won't remember to put the ": base()" on their constructors.  :-/

the base will always be constructed, if you do not especify one
version, the compiler will try to call the default (no paremeter) if
not exist you get an error
 
Back
Top