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); }- A. Compile-time error: peek was not declared in this scope
- B. Compile-time error: x is private
- C. 0
- 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
- 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}; //…
- Which line fails to compile? cpp struct P { const int id; }; int main() { P a{1}, b{2}; P c = a; // L1 a = b; // L2 }
- How many of these statements about implicitly generated special members in C++11 and later are correct? (i) If a class declares a copy…