Wizmann Wizmann - 1 year ago 55
C++ Question

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 {
virtual ~Abstract_base () = 0;
virtual void interface () const = 0;
virtual const char* mumble () const
return _mumble;
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~~ :)

Answer Source

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.


struct Base {
    virtual ~Base() = 0;
    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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download