Alexandru Irimiea
Alexandru Irimiea

Reputation: 2634

Compiler option to disable calling pure virtual methods from constructor

Referring to this question, How to resolve "pure virtual method called" is there a compiler option, that raises error when a virtual method is called from constructor/destructor? When there is a pure virtual method, the program will crash at runtime with segmentation fault.

This is proven many times to be a bad design:

When you call virtual methods from within your constructors/destructors it's not the overriden versions of them that are called.

EDIT:

I am asking specifically for MSVC, but it would be useful if there is an option for each compiler (GCC, CLANG, etc).

Upvotes: 0

Views: 876

Answers (2)

eerorika
eerorika

Reputation: 238441

is there a compiler option that raises error when a virtual method is called from constructor/destructor? When there is a pure virtual method, the program will crash at runtime with segmentation fault.

but it would be useful if there is an option for each compiler (GCC, CLANG, etc).

For GCC and Clang, the option is -Werror. This will cause all warnings to raise an error. If you directly call a pure virtual function in a constructor or destructor, both compilers warn by default.

There is of course no warning / error if a non-pure virtual function is called. It has well defined behaviour. Also, a compiler can not in general detect indirect calls to pure virtual functions.

I don't know of MSVC.

This is proven many times to be a bad design:

If you refer to calling a pure virtual function virtually in ctor./dtor., then bad design is an understatement. The behaviour is undefined. If you're unlucky, the program might not even crash.

Upvotes: 3

KimKulling
KimKulling

Reputation: 2843

I have not found any compiler switch for this in visual studio, but there is a handler in the Visual Studio Runtime for this: _purecall , which is located in the runtime file PureVirt.c . It will be called every time when there is no entry in the vtable for a virtual function, which is the case when you have a pure virtual call.

You can overload this function and add a DebugBreak

But this is just a workaround to get the callstack for your pure virtual call.

Upvotes: 0

Related Questions