ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
struct Base { virtual ~Base() {} };
struct Derived : Base {};
struct Other : Base {};
int main() {
Base *b = new Derived();
Other *o = dynamic_cast<Other*>(b);
cout << (o == nullptr);
}- A. 0
- B. 1
- C. Compile-time error: dynamic_cast requires a polymorphic source, but Base has none here
- D. Undefined behaviour
Correct answer: B. 1
Base has a virtual destructor, so it is polymorphic and dynamic_cast can check the real type at runtime. b actually points at a Derived, which is unrelated to Other, so the downcast fails safely and dynamic_cast returns a null pointer, making o == nullptr true (prints 1).
More OOP with C++ and Java questions
- What is printed? java class Animal { void speak() { System.out.print(".."); } } class Dog extends Animal { void speak() {…
- What is printed? cpp struct Base { public: virtual ~Base() { cout << "~Base "; } }; struct Derived : Base { int data = new int[10]…
- What is printed? cpp struct Vehicle { virtual string type() { return "Vehicle"; } }; struct Car : Vehicle { string type() override {…
- What is printed? java abstract class Shape { abstract double area(); String describe() { return "Area=" + area(); } } class Square extends…
- What is printed? java class Base { protected String name() { return "Base"; } public String greet() { return "Hi " + name(); } } class…
- What is printed? cpp struct A { virtual void f() { cout << "A"; } }; struct B : A { virtual void f() { cout << "B"; } }; struct C : B {…