Call pure virtual method runtime

I was wondering if there is a way to write a C++ program which compiles successfully but crashes runtime because of a call to a pure virtual method. Even if we don’t take ugly memory handling errors into account, there is:

 1 struct Base {
 2     Base() { init(); }
 3     void init() { init2(); }
 4     virtual void init2() = 0;
 5 };
 6 
 7 struct Derived :public Base {
 8     virtual void init2() {}
 9 };
10 
11 int main() {
12     Derived d;
13     return 0;
14 }

And it compiles and crashes like a charm vase:

1 $ g++ -Wall virtual.cpp 
2 $ ./a.out 
3 pure virtual method called
4 terminate called without an active exception
5 Aborted (core dumped)
6 $ 

The committed deadly sin was calling a virtual method in the constructor in a sneaky form.

Published: March 07, 2013.