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?
- A. It returns nullptr because the object is not a Derived
- B. It compiles and performs no run-time check; using the result as a Derived is undefined behaviour
- C. It throws std::bad_cast
- 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
- What is printed? cpp struct S { int a = 1; int b = 2; S() : a(10) { } S(int) { } }; int main() { S x; S y(0); cout << x.a << x.b << y.a; }
- What is printed? cpp struct B { virtual void f() { cout << "B"; } }; struct D : B { void f() override { cout << "D"; } }; int main() { D…
- What is printed? java class Util { static int say(String s) { System.out.print(s); return 1; } } interface I { int X = Util.say("I"); }…
- What is printed? java class P { static int v = 5; static { System.out.print("P"); } } class C extends P { static { System.out.print("C")…
- What is printed? java class C { static { System.out.print("init "); } } // in main: C[] a = new C[2]; Class<?> k = C.class…
- What is printed? java try { try { System.out.print("1"); throw new Exception("a"); } catch (Exception e) { System.out.print("2"); throw…