Search code examples
c++oopinheritanceconstructorpure-virtual

The constructor function in a pure virtual class should be "protected" or "public"?


The following example is from the book "Inside C++ object model"

class Abstract_base {
public:
    virtual ~Abstract_base () = 0;
    virtual void interface () const = 0;
    virtual const char* mumble () const 
    {
        return _mumble;
    }
protected:
    char *_mumble;
};

The author says if I want to initialize _mumble, the data member of the pure virtual base class, a "protected constructor" should be implemented.

But why protected? And why "public constructor" is not suitable for this class?

Thanks for your answers, and it would be perfect if there's an example.


Solution

  • It doesn't really matter, since you're not allowed to construct objects of the base class anyway. Making it protected serves only as a reminder of the fact that the class is supposed to be a base class; it's only cosmetics/documentation.

    Consider

    struct Base {
        virtual ~Base() = 0;
      protected:
        Base() { std::puts("Base constructor"); }
    };
    
    Base::~Base() { std::puts("Base destructor"); }
    
    struct Derived : Base {};
    
    int main()
    {
        //Base b;   // compiler error
        Derived d;
    
        Base *b = new Derived();
        delete b;
    }
    

    Removing the protected doesn't change the meaning of the program in any way.