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?
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.
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.
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.
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 .
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With