10
votes

I'm aware of the uses of private (and of course public) destructors.

I'm also aware of the uses of a protected destructor in a derived class:

Use a protected destructor to prevent the destruction of a derived object via a base-class pointer

But I've tried running the following code and it won't compile:

struct A{
    int i;
    A() { i = 0;}
    protected: ~A(){}
};

struct B: public A{
    A* a;
    B(){ a = new A();}
    void f(){ delete a; }
};


int main()
{
   B b= B();
   b.f();
   return 0;
}

I get:

void B::f()':
main.cpp:9:16: error: 'A::~A()' is protected

What am I missing?

If I called a protected method in A from inside f() it would work. So why is calling the d'tor different?

1
I guess this is a duplicate, you can't call protected member functions of base class objects other than *this in a derived class' member function.dyp
Related or duplicate: stackoverflow.com/q/13723217/420683dyp

1 Answers

13
votes

protected doesn't mean that your B can access the members of any A; it only means that it can access those members of its own A base... and members of some other B's A base!

This is in contrast to private, whereby some object with type A can always invoke the private members of another object with type A.