Search code examples
c++inheritanceconditional-compilation

Problems with ifdef based inheritance in C++


I was looking at the code of some class I was using, and I came across code like this:

#ifdef SOME_OBSCURE_CONDITION
class A {
#elif 
class A : public B {
#endif

Can there be any problems with such code?

Specifically, suppose file x.cpp includes y.h and z.h. z.h and y.h both include a.h (which defines class A), but additionally y.h defines SOME_OBSCURE_CONDITION. In this case, will two conflicting definitions of A not be present in x.cpp?


Solution

  • yes, the two variations simultaneously would violate the ODR (One Definition Rule) and may lead to anything ranging from

    • compile errors
    • link errors
    • undefined behaviour (including but not limited to crashing)

    As long as you can make sure that the SOME_OBSCURE_CONDITION define is globally identical (also across partial builds/relinks...) there will not be an issue.