ProgrammingHardProduct-company placement · C++

Base* b points to an object that is really a Base (not a Derived). What does static_cast<Derived*>(b) do?

  1. A. It returns nullptr because the object is not a Derived
  2. B. It compiles and performs no run-time check; using the result as a Derived is undefined behaviour
  3. C. It throws std::bad_cast
  4. D. It fails to compile unless Base is polymorphic

Correct answer: B. It compiles and performs no run-time check; using the result as a Derived is undefined behaviour

static_cast trusts the programmer for downcasts and adjusts the pointer without checking. Only dynamic_cast (which needs a polymorphic base) checks the real type and returns nullptr or throws for references.

More OOP with C++ and Java questions

Exams that ask this topic