The program below does not compile. Which statement correctly describes the problem?
main.cpp
#include <iostream>
class A {
int secret_ = 42;
friend class B;
};
class C;
class B {
friend class C;
};
class C {
public:
static int steal(const A& a) { return a.secret_; }
};
int main() {
A a;
std::cout << C::steal(a) << '\n';
return 0;
}
AB must have members
BFriendship is not transitive: C is a friend of B, and B is a friend of A, but C is not a friend of A
Csecret_ must be static
DC must be declared before A
Correct Answer: Option B
Only classes and functions named in A's own friend declarations get access to A's private members.
The program below does not compile. Which statement correctly describes the problem?
main.cpp
#include <iostream>
class Auditor;
class Ledger {
int total_ = 900;
friend int Auditor::check(const Ledger&);
};
class Auditor {
public:
int check(const Ledger& l) { return l.total_; }
};
int main() {
Ledger l;
Auditor a;
std::cout << a.check(l) << '\n';
return 0;
}
Acheck must be static
BAuditor is only forward-declared at the friend declaration, so Auditor::check is unknown; define Auditor (with check declared) before Ledger, or befriend the whole class
Ctotal_ must be public
Dfriend must be at the top of the class
Correct Answer: Option B
To befriend a single member function, the compiler must already have seen that function's declaration in the complete class.
The program below does not compile. Which statement correctly describes the problem?
main.cpp
#include <iostream>
class Temperature {
double c_;
public:
explicit Temperature(double c) : c_(c) {}
friend double to_kelvin(double celsius) { return celsius + 273.15; }
};
int main() {
std::cout << to_kelvin(25.0) << '\n';
return 0;
}
A273.15 must be an int
Bto_kelvin is a hidden friend defined only inside the class; it is found only by argument-dependent lookup, and its argument is a double, not a Temperature – so it is not visible here
CTemperature has no default constructor
Dfriend functions cannot return double
Correct Answer: Option B
A hidden friend should take the class type as a parameter. For a plain utility, declare it outside the class (or as a static member).
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·