ProgrammingHardProduct-company placement · C++
Which line fails to compile?
Which line fails to compile?
// C++17
struct S {
int v;
S(int x) : v(x) { }
bool operator==(const S& o) const { return v == o.v; }
};
int main() {
S s(1);
bool a = (s == 1); // L1
bool b = (1 == s); // L2
}- A. L1 only
- B. Both
- C. Neither
- D. L2 only
Correct answer: D. L2 only
For a member operator the left operand must already be an S; no implicit conversion is applied to it. In s == 1 the right operand converts via S(int). A non-member (friend) operator== allows conversions on both sides.
More OOP with C++ and Java questions
- What is printed? cpp struct B { void run() { step(); } virtual void step() { cout << "B"; } }; struct D : B { void step() override { cout…
- What is printed? cpp class A { int x = 3; friend int peek(const A& a) { return a.x; } }; int main() { A a; cout << peek(a); }
- Which function returns a reference that is SAFE to use after the call returns?
- Why does a C++ copy assignment operator conventionally return T& (that is, this)?
- What is printed? cpp // C++17 struct V { int d[2] = {1, 2}; int& operator[](int i) { cout << "N"; return d[i]; } int operator[](int i)…
- Which lines fail to compile? cpp struct E { explicit E(int) { } }; int main() { E a(1); // L1 E b{1}; // L2 E c = 1; // L3 E d = {1}; //…