Sunday, April 15, 2012

Oh C++, You're so Silly

Apparently destructors aren't the law in C++. The following code never calls ~B.

#include <iostream> class A { public: virtual void print(const std::string s) = 0; }; class B : public A { public: ~B(void) { std::cout << "Self-destruct." << std::endl; } void print(const std::string s) { std::cout << s << std::endl; } }; int main(int argc, char ** argv) { A * a = new B(); a->print("cows"); delete a; return 0; }% ./abstract cows %

Now what? Using reinterpret_cast instead doesn't get it to work.

Post a Comment