Search code examples
c++c++11conditional-operatorauto

auto with ternary operator and nullptr


Can I use auto with such usage of the ternary operator?

auto obj = some_cond ? static_cast<className*>(baseClassObj) : nullptr;

It compiles in Visual Studio, and the code works OK, but can there be any unexpected side effects? Or, will auto here always be className* and I can relax and write such code? Or, with the ternary operator, is it better to write this?

className* obj = some_cond ? static_cast<className*>(baseClassObj) : nullptr;

Solution

  • auto deduces to the type of the value that is assigned to it. The ternary operator can only return one type. nullptr is implicitly convertible to any pointer type, but no pointer type is implicitly convertible to std::nullptr_t, so in this example the ternary operator must always return className*, and thus auto will always deduce as className*.