Learn Something New Every Day – C++ Destructors
I was talking to a guy yesterday and something hit me like a ton of bricks - the virtual keyword in C++ really is just about polymorphism (the ability to have a pointer know the right type to call) and has nothing in the order the destructors are called.
In my (weak) defense, I've always used virtual destructors in C++ - just to be safe, but safe from what is the issue? While I knew the reason for the keyword virtual in C++ class definition, I was thinking that there was something special in the use on destructors. Something where it told the compiler to 'unwind' the destruction properly. Not so.
If I have the simple class structure:
#include <iostream> class GrandParent { public: GrandParent() { std::cout << "constructing GrandParent" << std::endl; } ~GrandParent() { std::cout << "destructing GrandParent" << std::endl; } }; class Parent : public GrandParent { public: Parent() : GrandParent() { std::cout << "constructing Parent" << std::endl; } ~Parent() { std::cout << "destructing Parent" << std::endl; } }; class Me : public Parent { public: Me() : Parent() { std::cout << "constructing Me" << std::endl; } ~Me() { std::cout << "destructing Me" << std::endl; } }; int main(int argc, char *argv[]) { Me a; return(0); }
we get the output:
peabody{drbob}30: a.out constructing GrandParent constructing Parent constructing Me destructing Me destructing Parent destructing GrandParent
Which confirms the conversation I had with this C++ developer that the only reason that the keyword virtual would be used on the destructor is if you had a GrandParent pointer that was really pointing to an instance of Me and you wanted to make sure that the destructors for Me and Parent were called along with the destructor for GrandParent.
I made the silly assumption, and this guy was right. I'm glad we had the talk we did, as I'm going to question a lot of the assumptions I've been holding on to regarding C++ coding because of it. Interesting talk. Never too old to learn.