I wrote this test code that uses three types: struct One is a regular type without virtual members, struct Two : One has a pure virtual function and a virtual destructor, and struct Three : Two implements the Two interface.
#include <iostream> struct One { ~One() { std::cout << "~One()\n"; } }; struct Two : One { virtual ~Two() { std::cout << "~Two()\n"; } virtual void test() = 0; }; struct Three : Two { virtual ~Three() { std::cout << "~Three()\n"; } virtual void test() { std::cout << "Three::test()\n"; } }; int main() { Two* two = new Three; two->test(); One* one = two; delete one; }
Not surprisingly, the result was :
Three :: test ()
~ One ()
Is there a way to fix this differently than making each destructor virtual? Or should programmers be careful not to run into this situation? It seems strange to me that there are no warnings when compiling this.
source share