Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I inherit constructors?

Tags:

c#

dry

I know it's not possible to inherit constructors in C#, but there's probably a way to do what I want to do.

I have a base class that is inherited by many other classes, and it has an Init method that does some initializing taking 1 parameter. All other inheriting classes also need this initializing, but I'd need to create separate constructors for all of them that would like like this:

public Constructor(Parameter p) {     base.Init(p); } 

That totally violates the DRY principles! How can I have all necessary stuff initialized without creating dozens of constructors?

like image 680
Alex Avatar asked Oct 06 '10 14:10

Alex


People also ask

Why can't a constructor be inherited?

In simple words, a constructor cannot be inherited, since in subclasses it has a different name (the name of the subclass). Methods, instead, are inherited with "the same name" and can be used.

Is it possible to inherit constructor in C++?

To inherit only selected ones you need to write the individual constructors manually and call the base constructor as needed from them. Historically constructors could not be inherited in the C++03 standard. You needed to inherit them manually one by one by calling base implementation on your own.


1 Answers

You don't need to create loads of constructors, all with the same code; you create only one, but have the derived classes call the base constructor:

public class Base {     public Base(Parameter p)     {         Init(p)     }      void Init(Parameter p)     {         // common initialisation code     } }  public class Derived : Base {     public Derived(Parameter p) : base(p)     {       } } 
like image 147
Rob Levine Avatar answered Oct 11 '22 03:10

Rob Levine