views:

112

answers:

2

As an abstract class cannot be instantiated, why is a constructor still allowed inside the abstract class?

public abstract class SomeClass 
 {  
     private string _label;

     public SomeClass(string label)  
     {  
         _label=label;
     }  
}
+11  A: 

Constructors of any derived class still have to call a constructor in the abstract class. If you don't specify any constructors at all, all derived classes will just have to use the default parameterless one supplied by the compiler.

It absolutely makes sense to have a constructor - but "public" is really equivalent to "protected" in this case.

Jon Skeet
+2  A: 

Because you can still do the following:

public class SomeChildClass : SomeClass
{
    public SomeChildClass(string label) : base(label){ }

    public string GetLabel() { return _label; }
}

As you can see, the child class can call the base contructor (on the abstract class) to create an instance of itself.

Like Jon said though, public really isn't necessary. It's effectively the same as protected.

Justin Niessner