The last line of this code fails to compile with castingAndTernary.cpp:15: error: conditional expression between distinct pointer types ‘D1*’ and ‘D2*’ lacks a cast
The [ternary] conditional operator requires its second and third operands to have the same type.
b = boolean_expression ? new D1 : new D2;
You have the distinct types D1*
and D2*
. As the error message indicates, you have to ensure the correct type with an explicit conversion (i.e. a cast):
b = boolean_expression ? static_cast(new D1) : static_cast(new D2);
The standard says that compilers must require this (instead of just doing an implicit conversion), so that's what your compiler requires.