Constructor invokation

  • Thread starter Thread starter Alex
  • Start date Start date
A

Alex

Given this base class:

class Base
{
Base(){}
}

Are these the same:

class Test : Base
{
Test(){}
}

class test: Base
{
Test():base(){}
}
 
Hi Alex,

Yes, it's my understanding that the :Base() is assumed in the case of
Test() {}.

Regards,
Fergus
 
Hi Alex,

Yes in that case is the same, he thing is that if you do not especify a
constructor to call the compiler takes the default one.
A similar thing will happen if the Base class does not defined any
constructor, in this case the compiler create one and everything is as
explained.

Now a different thing happen when you declare a constructor in Base taking a
parameter. in this situation you MUST declare a default constructor
otherwise the compiler will give you error.
A couple of examples:
class A
{

}
class B:A
{
B(){}
}

this will compile ok, cause the compiler will generate the constructor for A
but this:
class A
{
public A(int b){}
}
class B:A
{
B(){}
}

will give you this error: " No overload for method 'A' takes '0' arguments"

Hope this help,
 
Ignacio Machin said:
Now a different thing happen when you declare a constructor in Base taking a
parameter. in this situation you MUST declare a default constructor
otherwise the compiler will give you error.

Not if you make all your constructors call a base constructor with a
parameter. For instance:

class Base
{
public Base (int b){}
}

class Derived
{
public Derived (int a, int b) : base (b)
{
}
}

compiles fine.

One further bit of terminology - you can never declare a default
constructor; a default constructor is what is supplied by the compiler
if you don't declare any constructors. You can, however, declare a
parameterless constructor.

See http://www.pobox.com/~skeet/csharp/constructors.html for more
information.
 
Back
Top