views:

92

answers:

3

Is there any relevance of a 'public' constructor in an abstract class? I can not think of any possible way to use it, in that case shouldn't it be treated as error by compiler (C#, not sure if other languages allow that).

Sample Code:

internal abstract class Vehicle
{
    public Vehicle()
    {            
    }
}

The C# compiler allows this code to compile, while there is no way i can call this contructor from the outside world. It can be called from derived classes only. So shouldn't it allow 'protected' and 'private' modifiers only. Please comment.

A: 

Yes, a public ctor on an abstract class is meaningless and a bit misleading as it will behave as protected in that only derived classes may call it.

A private ctor will have little meaning outside of interesting edge cases.

A protected ctor would make sense if required by derived classes.

Sky Sanders
A `private` constructor does makes sense in an abstract class.
dan04
@dan- happy? ;-)
Sky Sanders
+3  A: 

THere's no reason for a public constructor for an abstract class. I'd assume that the reason that the compiler doesn't complain is as simple that they just didn't spend time covering that since it really doesn't matter if it's public or protected.

ho1
+1  A: 

Dupe: there is another question on SO just like this: Abstract class constructor access modifier

The answers on that question come down to the same thing in the end: it does not really matter if you declare it protected or public.

Also there seems to be some discussion about it in literature (e.g. in Framework Design Guidelines). This is referenced in this blogpost: Good design or bad design of abstract class?

scherand