ProgrammingHardProduct-company placement · C++
What is printed?
What is printed?
struct B { virtual ~B() { } };
struct D : B { };
struct E : B { };
int main() {
B* p = new D;
cout << (dynamic_cast<D*>(p) != nullptr) << (dynamic_cast<E*>(p) != nullptr);
try { E& e = dynamic_cast<E&>(*p); cout << "ok"; }
catch (std::bad_cast&) { cout << "bad"; }
}- A. 11ok
- B. 10bad
- C. 10ok
- D. 00bad
Correct answer: B. 10bad
dynamic_cast checks the actual object: a D is not an E, so the pointer cast yields nullptr. A failed cast to a REFERENCE cannot return null and throws std::bad_cast instead.
More OOP with C++ and Java questions
- What is printed? cpp struct A { }; struct B : A { }; struct P { virtual ~P() { } }; struct Q : P { }; int main() { B b; Q q; A& ra = b; P&…
- What is printed? cpp struct A { A(int x) { cout << x; } A() { cout << 0; } }; struct B : virtual A { B() : A(1) { cout << "B"; } }; struct…
- What is printed? cpp void f(long) { cout << "L"; } void f(double) { cout << "D"; } int main() { f(5L); f(2.5f); f(5); }
- What is printed? cpp struct B { int b; B(int x) : b(x) { } }; struct D : B { int d; D(int x, int y) : B(x), d(y) { } }; int main() { D…
- How many of these statements about C++ dynamic memory are correct? (i) Memory obtained with new[] must be released with delete[]. (ii)…
- What happens when this is compiled? cpp struct K { const int c; int& r; K(int& x) { c = 1; r = x; } };