ProgrammingModerateProduct-company interview pattern
What is printed?
What is printed?
class A {
public:
int x;
A(int v) : x(v) {}
};
int main() {
A a(5);
A b = a;
b.x = 9;
cout << a.x << b.x;
}- A. 99
- B. 59
- C. 55
- D. 95
Correct answer: B. 59
A b = a copies the object (memberwise, by the implicit copy constructor); b is independent of a. Changing b.x leaves a.x at 5. 99 is what Java-style reference semantics would give, but C++ objects are values.
More OOP with C++ and Java questions
- Which line fails to compile? java abstract class Shape { abstract double area(); } class Sq extends Shape { double area() { return 4; } }…
- What is printed? java class K { K() { this(5); System.out.print("A"); } K(int x) { System.out.print("B" + x); } } // in main: new K();
- Which line fails to compile? java final int[] arr = {1, 2, 3}; arr[0] = 10; // L1 arr = new int[3]; // L2 System.out.print(arr[0]); // L3
- What is printed? java class P { static int c = 0; P() { c++; } } class Q extends P { Q() { c += 10; } } // in main: new P(); new Q(); new…
- What is printed? java class A { int x = 10; A() { x = 20; } { x = 30; } } // in main: System.out.print(new A().x);
- What is printed? java interface I { default String who() { return "I"; } } class P { public String who() { return "P"; } } class C extends…