11

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?

matanc1
  • 6,525
  • 6
  • 37
  • 57
  • 6
    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 Oct 19 '13 at 17:31
  • Related or duplicate: http://stackoverflow.com/q/13723217/420683 – dyp Oct 19 '13 at 17:34
  • possible duplicate of [cannot call base class protected functions?](http://stackoverflow.com/questions/477829/cannot-call-base-class-protected-functions) – Mat Oct 19 '13 at 17:34

1 Answers1

14

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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • 2
    A member function of class `B` can also access the protected members declared in class `A` of another object, given that this object is of type `B` or derived from `B`. It's quite confusing. – dyp Oct 19 '13 at 17:36
  • 1
    I shall `public`ly upvote you in a `protected` fashion. Wanna meet in `private` later? –  Oct 19 '13 at 17:42
  • @DyP: Oh, yes, that's true. – Lightness Races in Orbit Oct 19 '13 at 18:00
  • 1
    So, what happens in a polymorphic scenario where the `A*` is actually used to allocate a `B` instance during the runtime - `B` doesn't know whether the actual instance is of type A or B? A no go because of using a base pointer even though it is a B instance? – dtech Oct 19 '13 at 19:58
  • 1
    @ddriver: That's right! Virtual dispatch works for function calls but access restrictions are applied first. – Lightness Races in Orbit Oct 19 '13 at 20:14