ProgrammingVery hardProduct-company MCQ pattern
What is printed?
What is printed?
struct B {
virtual void f(int x = 1) { cout << "B" << x; }
};
struct D : B {
void f(int x = 2) override { cout << "D" << x; }
};
int main() {
B *p = new D;
p->f();
}- A. D1
- B. D2
- C. B1
- D. B2
Correct answer: A. D1
The function body is chosen at run time (D::f), but default arguments are filled in at compile time from the static type B*, so x = 1. Never give an override a different default argument.
More OOP with C++ and Java questions
- What is printed? java class T { static String hi() { return "hi"; } } // in main: T t = null; System.out.print(t.hi());
- What is printed? java char x = 'A'; int i = 0; System.out.print(true ? 1 : 2.0); System.out.print(" "); System.out.print(true ? x : i);
- What is printed? cpp struct B { void f(int) { cout << "Bi"; } void f(double) { cout << "Bd"; } }; struct D : B { void f(double) { cout <<…
- How many of these are correct about C++ virtual functions on a typical implementation? (i) Each class with virtual functions has a table…
- A method call such as shape.area() runs different code depending on whether shape refers to a Circle or a Square object at run time. Which…
- A Java class declares only the constructor Account(String id) and no other constructor. What happens with the statement new Account()?