ProgrammingHardProduct-company placement · C++
Which line fails to compile?
Which line fails to compile?
struct P {
int x = 3;
ostream& operator<<(ostream& os) { return os << x; }
};
int main() {
P p;
cout << p; // L1
p << cout; // L2
}- A. L2 only
- B. L1 only
- C. Both
- D. Neither
Correct answer: B. L1 only
A member operator<< takes the object as its LEFT operand, so it is invoked as p << cout. cout << p would need a non-member operator<<(ostream&, const P&), which is why stream operators are written as free (often friend) functions.
More OOP with C++ and Java questions
- What is wrong with this program? cpp struct Buf { int p; Buf() : p(new int[4]) { } ~Buf() { delete[] p; } }; int main() { Buf a; Buf b =…
- What happens when this is compiled? cpp struct A { int v = 0; int& get() const { return v; } };
- A global object g1 defined in file1.cpp uses the global object g2 defined in file2.cpp inside g1's constructor. Both have dynamic…
- What is printed? cpp void f(int) { cout << "I"; } void f(char) { cout << "P"; } int main() { f(0); f(nullptr); }
- Which lines fail to compile? cpp void g(int& x) { } void h(const int& x) { } int main() { int a = 1; g(5); // L1 h(5); // L2 g(a); // L3…
- What is printed? cpp void f(int&) { cout << "N"; } void f(const int&) { cout << "C"; } int main() { int a = 1; f(a); f(5); }