Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a public constructor in an abstract class a codesmell? [closed]

Tags:

c++

Is a public constructor in an abstract class a codesmell? Making the constructor protected provides all of the access of which you could make any use. The only additional access that making it public would provide would be to allow instances of the class to be declared as variables in scopes that cannot access its protected members, but instances of abstract classes cannot be declared at all.

like image 416
TheBeardyMan Avatar asked Sep 01 '09 15:09

TheBeardyMan


People also ask

Can we have public constructor in abstract class?

Constructors on abstract types can be called only by derived types. Because public constructors create instances of a type and you cannot create instances of an abstract type, an abstract type that has a public constructor is incorrectly designed.

Are the constructors in an abstract class private?

Answer: Yes. Constructors in Java can be private. All classes including abstract classes can have private constructors. Using private constructors we can prevent the class from being instantiated or we can limit the number of objects of that class.

Can abstract class have constructor block?

An abstract class can have constructors like the regular class. And, we can access the constructor of an abstract class from the subclass using the super keyword.


2 Answers

I'd say its a bad sign for a couple of reasons.

The first is that it might mislead somebody into thinking they can actually call that routine.

The second is that it implies the author thought you could call it. You now don't know if that was an important part of his design or not.

like image 183
T.E.D. Avatar answered Sep 16 '22 15:09

T.E.D.


I've read it in at least one coding guideline that constructors of abstract classes should not be public - I think that rule makes sense for the reason you gave.

However, i can't imagine a scenario where making it public would make things go wrong. So i wouldn't go so far as saying it's a code smell. I see the protected constructor as a "nice to have" property :)

like image 28
Johannes Schaub - litb Avatar answered Sep 18 '22 15:09

Johannes Schaub - litb