Is a public constructor in an abstract class a codesmell?

My opinion would be that the public constructor might be seen to be confusing, and as you say making it protected would be correct. I would say that a protected constructor correctly reinforces the impression that the only sensible use of an abstract class is to derive from it.

In fact, you only need to declare a constructor in an abstract class if it needs to do something, eg. initialise its own private members. I would then expect there to be other protected member functions that are helpful to derived classes.

EDIT:

Since no-one has posted any code and @sbi asked for some in a comment to OP, I thought I would post some:

class Base:
{
public:           // The question is: should the ctor be public or protected?
// protected:
    Base():i(0){} // ctor is necessary to initialise private member variable
public:
    virtual ~Base(){} // dtor is virtual (but thats another story)
                  // pure virtual method renders the whole class abstract
    virtual void setValue(void)=0;  
protected:
    int getValue(void){ return i;}
private:
    int i;
};

Base b1;  // Illegal since Base is abstract, even if ctor is public
Base& b2=makeBase();  //We can point to, or refer to a Base
b2.setValue();    // We're not sure what this does, but we can call it.
b2.getValue();    // Illegal since getValue is protected

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 :)


As you say, there is no need to provide public constructor of abstract class, nor it can be misused, if you provide public constructor.

However, you may consider declaring constructor as public as recomendation for structuring classes derived from the abstract one.

Tags:

C++