views:

91

answers:

3

Hello, I have a class structure like

abstract class Animal {
  public Animal(){
    //init stuff..
  }
}

class Cat : Animal {
  public Cat(bool is_keyboard) : base() //NOTE here
  {
    //other init stuff
  }
}

Now then, look at the noted line. If you remove : base() then it will compile without an error.

Why is this? Is there a way to disable this behavior?

+7  A: 

There is an implicit : base() if you don't add anything else (any : base(...) or : this(...)). To force it to be explicit, add a parameter to the base-constructor(s). Then it can't be implicit.

For example:

public Animal(string name) {...}
Marc Gravell
Cool, you learn something everyday... I've always explicitly put base(), probably will continue to do so because how many developers realise there is an implicit call to it?
slugster
Also, I found Skeet's nifty article that told me all about it: http://www.yoda.arachsys.com/csharp/constructors.html
Earlz
@slugster, I didn't realize it... so yea.
Earlz
A: 

Hi Earlz,

Why is this?

This article explains it.

Is there a way to disable this behavior?

Nope. I'm sorry (but ... See mark answer for a workaround : )

SDReyes
+2  A: 

17.10.4 Default Constructors:

If a class contains no instance constructor declarations, a default instance constructor is automatically provided. 2 That default constructor simply invokes the parameterless constructor of the direct base class. 3 If the direct base class does not have an accessible parameterless instance constructor, a compile-time error occurs. 4 If the class is abstract then the declared accessibility for the default constructor is protected. 5 Otherwise, the declared accessibility for the default constructor is public

Darin Dimitrov
While true, that is the wrong section for what happens when ` : base()` is removed. That section tells what happens if the entire constructor is removed.
Marc Gravell