ProgrammingVery hardProduct-company placement · C++

What is printed?

What is printed?
class A {
    int x = 3;
    friend int peek(const A& a) { return a.x; }
};
int main() { A a; cout << peek(a); }
  1. A. Compile-time error: peek was not declared in this scope
  2. B. Compile-time error: x is private
  3. C. 0
  4. D. 3

Correct answer: D. 3

A friend function defined inside the class is not a member and is not visible to ordinary lookup, but argument-dependent lookup finds it because its argument is an A (a 'hidden friend'). As a friend it may read the private x.

More OOP with C++ and Java questions

Exams that ask this topic