tru7
tru7

Reputation: 7222

Can you tell if a function is pure virtual at runtime in c++

I am with a very sporadic bug where a virtual function looks to have become "pure" at runtime. It must be some memory corruption, apparently the object has not been destroyed but it may have been overwritten somewhere.

The debugger shows one of the pointers in the virtual functions list as NULL.

The question is, can you tell at runtime if a function is == NULL?

&(object->function)==NULL

is giving compile error "illegal operation on bound member function expression"

EDIT: With that sentence what I want to do is to put some checks around to see if I can intercept the situation (function address being 0x00000000) at runtime before the point of the crash. Showing the code would be a bit long as the object with the problematic function may have been around some time and gone through many processes so I don't expect a solution on the actual problem. I am just wondering if I can place some tests around to detect early the corruption (the bug is veeery sporadic)

Upvotes: 0

Views: 572

Answers (1)

Ulrich Eckhardt
Ulrich Eckhardt

Reputation: 17434

Calls to pure virtual functions happen if you invoke the virtual function before the derived class (the one implementing the virtual function) is constructed or after it is destroyed. Formally, this causes undefined behaviour, too. You might be able to add a flag that you set in the concrete derived class' ctor and reset in the dtor and then check that flag, which is an ugly hack though. You could also check the type using typeid, but that method is more complex and thus more likely to cause further issues.

One advise though: You should make sure systematically that such problems can't happen in the future. Sometimes a small detour that guarantees correct code is worth it!

Upvotes: 2

Related Questions