Is there any way to call a field destructor before the class destructor?
Suppose I have 2 classes Small and Big, and Big contains an instance of Small as its field as such:
class Small
{
public:
~Small() {std::cout << "Small destructor" << std::endl;}
};
class Big
{
public:
~Big() {std::cout << "Big destructor" << std::endl;}
private:
Small small;
};
int main()
{
Big big;
}
This, of course, calls the big destructor before the small destructor:
Big destructor
Small destructor
I need the Small destructor to be called before the Big destructor since it does some cleanup necessary for the Big destructor.
I could:
- call the
small.~Small()destructor explicitly. -> This, however, calls theSmalldestructor twice: once explicitly, and once after theBigdestructor has been executed. - have a
Small*as the field and calldelete small;in theBigdestructor
I am aware that I can have a function in the Small class that does the cleanup and call it in the Big destructor, but I was wondering if there was a way to inverse the destructor order.
Is there any better way to do this?