Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we call protected destructors from a derived class?

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?

like image 959
matanc1 Avatar asked Oct 19 '13 17:10

matanc1


People also ask

Why derived class destructor is called first?

The derived class must be constructed after the base class so that the derived class constructor can refer to base class data. For the same reason, the derived class destructor must run before the base class destructor. It's very logical: we construct from the inside out, and destroy from the outside in.

How do you call a derived class destructor?

You never need to explicitly call a destructor (except with placement new). A derived class's destructor (whether or not you explicitly define one) automagically invokes the destructors for base class subobjects. Base classes are destructed after member objects.

Can destructor be protected?

If the base class destructor is private or protected then you cannot call delete through the base-class pointer. Use a protected destructor to prevent the destruction of a derived object via a base-class pointer. It limits access to the destuctor to derived classes.

Do derived classes inherit destructors?

Derived classes do not inherit or overload constructors or destructors from their base classes, but they do call the constructor and destructor of base classes. Destructors can be declared with the keyword virtual .


1 Answers

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.

like image 101
Lightness Races in Orbit Avatar answered Oct 18 '22 20:10

Lightness Races in Orbit