ProgrammingModerateMicrosoft/Amazon SDE MCQ · GATE CS
What is printed?
What is printed?
struct E { virtual const char* w() const { return "E"; } };
struct F : E { const char* w() const override { return "F"; } };
int main() {
try { throw F(); } catch (E e) { cout << e.w(); }
try { throw F(); } catch (E& e) { cout << e.w(); }
}- A. FF
- B. EF
- C. EE
- D. FE
Correct answer: B. EF
Catching by value copy-initialises an E from the F, slicing it, so w() gives E. Catching by reference binds to the thrown F object, so the virtual call gives F.
More OOP with C++ and Java questions
- What is printed? cpp struct E { }; struct F : E { }; int main() { try { try { throw F(); } catch (E& e) { throw e; } } catch (F&) { cout…
- What is printed? cpp struct S { void f() { cout << "n"; } void f() const { cout << "c"; } }; int main() { S a; const S b{}; a.f(); b.f()…
- What is printed? cpp template <class T> void f(T) { cout << "T"; } template <> void f<int>(int) { cout << "S"; } template <class T> void…
- What is printed? cpp struct T { T() { } T(const T&) { cout << "C"; } T& operator=(const T&) { cout << "A"; return this; } }; int main() {…
- What is printed? cpp struct T { ~T() { cout << "d"; } }; T make() { return T(); } int main() { const T& r = make(); cout << "x"; }
- What is printed? cpp struct K { int g() { static int c = 0; return ++c; } }; int main() { K a, b; a.g(); b.g(); cout << a.g(); }