ProgrammingHardMicrosoft/Google SDE MCQ · GATE CS
Which line fails to compile?
Which line fails to compile?
struct M {
int v;
M(int x) : v(x) { }
M operator+(const M& o) const { return M(v + o.v); }
};
int main() {
M a(1);
M b = a + 2; // line 1
M c = 2 + a; // line 2
M d = a + a; // line 3
}- A. Line 1
- B. Line 3
- C. Line 2
- D. None of them
Correct answer: C. Line 2
A member operator+ needs an M on the left. In a + 2 the 2 converts to M through the non-explicit constructor, but in 2 + a no conversion is applied to the left operand for a member call, so it fails. A non-member operator+ would accept both.
More OOP with C++ and Java questions
- What is printed? cpp int main() { vector<int> a(3, 5); vector<int> b{3, 5}; vector<int> c; c.reserve(10); cout << a.size() << b.size() <<…
- Which line fails to compile? cpp struct S { int v = 1; static int count; static int get() { return v; } // line 1 static int all() {…
- What is printed? cpp struct B { virtual void f() { cout << "B"; } void g() { f(); } }; struct D : B { void f() override { cout << "D"; }…
- Which statement about this class is correct? cpp struct Buf { int p; Buf() : p(new int[8]) { } ~Buf() { delete[] p; } }; void use() { Buf…
- What is printed? cpp struct A { int x; A(int v) : x(v) { } }; struct B : A { int y; B(int v) : A(v 2), y(x + 1) { } }; int main() { B…
- What is printed? cpp struct B { B() { cout << "b"; } ~B() { cout << "~b"; } }; struct D : B { D() { cout << "d"; } ~D() { cout << "~d"; }…