3

My BaseClass Constructor is called whereas I have a constructor in derived class so when would I need to call base() ?

class BaseClass
{
    public BaseClass()
    {
        Debug.Print("BaseClass");
    }
}

class InheritedClass : BaseClass
{
    public InheritedClass()
    {
        Debug.Print("InheritedClass");
    }
}

private void Form1_Load(object sender, EventArgs e)
{
    InheritedClass inheritedClass = new InheritedClass();
}

Output

'Inheritance.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\Accessibility\v4.0_4.0.0.0__b03f5f7f11d50a3a\Accessibility.dll'
'Inheritance.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
BaseClass
InheritedClass
The thread 'vshost.RunParkingWindow' (0x12b4) has exited with code 0 (0x0).
The thread '<No Name>' (0x85c) has exited with code 0 (0x0).
The program '[4368] Inheritance.vshost.exe: Program Trace' has exited with code 0 (0x0).
The program '[4368] Inheritance.vshost.exe: Managed (v4.0.30319)' has exited with code 0 (0x0).
Markus Safar
  • 6,324
  • 5
  • 28
  • 44
user310291
  • 36,946
  • 82
  • 271
  • 487
  • No this is not a duplicate. The other question was about how to do thin g in a precise context. My question is about which contextS. – user310291 Jun 11 '14 at 15:18

2 Answers2

9

When you have a non-default base constructor(e.g. with param overloads).

Example:

public class BaseClass
{
  public BaseClass(int number)
  {
     // DoSomething
  }

  public BaseClass(string str)
  {
    // Do Something
  }
}

public class DerivedClass : BaseClass
{
   public DerivedClass(): base(7){} 
   public DerivedClass(string str) : base(str){}
}
MPelletier
  • 16,256
  • 15
  • 86
  • 137
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
0

The default base() constructor itself is called automatically.

public class DerivedClass : BaseClass
{
   public DerivedClass(): base() // No harm done, but this is redundant
   {}
   //same as
   public DerivedClass()
   {}
}

The only time it is not called automatically is when something else, like a parametered base constructor is called. Exactly as in Amir Popovich's excellent answer.

MPelletier
  • 16,256
  • 15
  • 86
  • 137