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 int g(int x = 10) { return x; } };
struct B : A { int g(int x = 20) override { return x * 2; } };
int main() {
    B b; A& r = b; B& s = b;
    cout << r.g();
    cout << " ";
    cout << s.g();
}
  1. A. 10 20
  2. B. 20 40
  3. C. 20 20
  4. D. 40 40

Correct answer: B. 20 40

r.g() runs B::g with A's static default 10 giving 20; s.g() uses B's default 20 giving 40.

More OOP with C++ and Java questions

Exams that ask this topic