Search code examples
c++gdb

How do I trap a pure virtual method called error?


I occasionally get this error

pure virtual method called
terminate called without an active exception
  1. it isn't possible to instantiate an abstract class in C++, so how is it even possible to get this situation
  2. How can I track this error down ? The complication here is that one process launches a child process, so it could be in the child or in the parent.

I've added a number of try/catch blocks to the code, but is there some tool that can help trap this error ?

valgrind is not usable in my situation since this is a high speed encoder with high memory usage, so it takes forever to run.

Any tips or clues would be most welcome.


Solution

  • In GCC/on systems using the Itanium ABI, you can define the function __cxa_pure_virtual. This is the function that gets called when a pure virtual function would have gotten invoked that doesn't have another definition.

    By default, it just prints "pure virtual method called" then terminates. You can make it throw an exception with a stack trace or have a break point:

    extern "C" void __cxa_pure_virtual() {
        trap_signal();
        gdb_breakpoint();
        print_stacktrace();
        throw std::runtime_error("pure virtual function called");
    }