Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the base() constructor not necessary?

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?

like image 518
Earlz Avatar asked Mar 31 '10 20:03

Earlz


2 Answers

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) {...}
like image 105
Marc Gravell Avatar answered Oct 14 '22 22:10

Marc Gravell


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

like image 37
Darin Dimitrov Avatar answered Oct 14 '22 21:10

Darin Dimitrov