Last active
October 2, 2017 22:02
-
-
Save mruzicka/c527df43e92a578bc56e8bee7788ae58 to your computer and use it in GitHub Desktop.
Virtual destructor test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Virtual destructor test | |
* ----------------------- | |
* compile using: | |
* cc -std=c++11 -o destructor_test destructor_test.cc -lstdc++ | |
* | |
* when class `A` does not define a virtual destructor the program prints: | |
* data constructed | |
* rationale: | |
* when a pointer typed to class `A` is used to delete an instance of class | |
* `B` (which is a subclass of `A`) the instance is not destructed properly | |
* as only the `A`'s destructor is called | |
* | |
* when class `A` _does_ define a virtual destructor the program prints: | |
* data constructed | |
* data destructed | |
* rationale: | |
* a default destructor for class `B` is generated by the compiler and since | |
* the base class `A` declares a virtual destructor the generated destructor | |
* overrides that from the base class, so when a pointer typed to class `A` | |
* is used to delete an instance of class `B` the instance is destructed | |
* properly as the `B`'s destructor is called | |
*/ | |
#include <iostream> | |
class A { | |
public: | |
virtual ~A() = default; | |
}; | |
template <typename T> | |
class B : public A { | |
T data; | |
}; | |
class D { | |
public: | |
D() { | |
std::cout << "data constructed" << std::endl; | |
} | |
~D() { | |
std::cout << "data destructed" << std::endl; | |
} | |
}; | |
int main(int argc, char *argv[]) { | |
A *a_p = new B<D>; | |
delete a_p; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment