Possible Duplicate:
Why can’t I create an abstract constructor on an abstract C# class?
Why I can't declare abstract an constructor of my class like this:
public abstract class MyClass { public abstract MyClass(int param); }
A constructor is a method called when a class is instantiated, and an abstract class cannot be instantiated. It sounds counterintuitive, right? In this article, we'll see why abstract classes can have constructors and how using them provides benefits in subclasses instantiation.
Constructor is always called by its class name in a class itself. A constructor is used to initialize an object not to build the object. As we all know abstract classes also do have a constructor.
yes it is. And a constructor of abstract class is called when an instance of a inherited class is created.
Yes, an abstract class can have a constructor, even though an abstract class cannot be instantiated.
Constructors are only applicable to the class in which they are defined, that is, they are not inherited. Base class constructors are used (you have to call one of them, even if only calling the default one automatically) but not overridden by deriving classes. You can define a constructor on an abstract base class -- it can't be used directly, but can be invoked by deriving classes. What you can't do is force a derived class to implement a specific constructor signature.
It is perfectly reasonable to have a constructor defined, typically as protected, in order to define some common set up code for all derived classes. This is especially true, perhaps, when the abstract class provides some other default behavior which relies on this set up. For example:
public abstract class Foo { public string Name { get; private set; } protected Foo( string name ) { this.Name = name; } } public class Bar : Foo { public Bar() : base("bar") { ... } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With