ProgrammingVery hardInfosys DSE · Wipro Elite
What is printed? (C++17; assume <iostream>, <string>, <vector> and using namespace std)
What is printed? (C++17; assume <iostream>, <string>, <vector> and using namespace std)
struct A { virtual void p() { cout << "A"; } };
struct B : A { int z; void p() override { cout << "B"; } };
void f(A a) { a.p(); }
int main() { B b; f(b); A& r = b; r.p(); A c = b; c.p(); }- A. BBB
- B. ABA
- C. AAA
- D. BAB
Correct answer: B. ABA
f(A a) and A c = b slice the object to a pure A, so A::p runs; only the reference r keeps the dynamic type B.
More OOP with C++ and Java questions
- What is printed? (C++17; assume <iostream>, <string>, <vector> and using namespace std) cpp struct X { string n; X(const char s) : n(s) {…
- What is printed? (C++17; assume <iostream>, <string>, <vector> and using namespace std) cpp struct A { A() { f(); } virtual void f() {…
- What is printed? (C++17; assume <iostream>, <string>, <vector> and using namespace std) cpp struct A { virtual ~A() { f(); } virtual void…
- What is printed? (C++17; assume <iostream>, <string>, <vector> and using namespace std) cpp struct T { T() { cout << "d"; } T(const T&) {…
- What is printed? (no move constructor is declared) (C++17; assume <iostream>, <string>, <vector> and using namespace std) cpp struct T {…
- What is printed? (C++17; assume <iostream>, <string>, <vector> and using namespace std) cpp struct C { static int n; int id; C() : id(++n)…