When an inherited class is created using the default constructor, does it also invoke the base class's constructor?

Does anyone know what this behavior is for C #? Is this the same for all .NET languages?

+3
source share
5 answers

Yes - this happens with any constructor in a derived class, unless you explicitly call the constructor of the base class.

class Base
{
  Base(){}
  Base(int i){}
}

class Derived : Base
{
  Derived(bool x) {} // calls Base.Base()
}

class Derived2 : Base
{
  Derived2() : base(10) {} // calls Base.Base(int)
}
+4
source

Yes, it automatically calls the default constructor of the base class. The default constructor has no parameters.

If there is no default constructor, you must manually call the base class constructor using the syntax:

public MyClass() : base(parameters, ...)

Source: Using Constructors (C #)

+6
source

, . , .

public class A
{
    public A(string s)
    {}
}

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

.

+1

# - , , IL.

:

class Parent { }
class Child : Parent { }

IL, Child, :

L_0001: call instance void Parent::.ctor()

, Parent.

+1

, OO , . , , .

- (, ), , , , , .

0

All Articles