I saw some code in C++ and have a question about it:
class CRectangle {
int width, height;
public:
friend CRectangle duplicate (CRectangle);
};
The variables width
and height
are private, and the method duplicate()
is public. The keyword friend
is for accessing the private and protected functions outside of a CRectangle
object, but duplicate()
is already public. If it can be accessed from the outside, why do we need "friend"?
Does this mean that, although we directly call a public method like duplicate()
outside of the class, if the method accesses some private variable, it is also not allowed and we have to declare it as "friend?"
This is the implementation of the duplicate()
function; I just want to make the question clear:
CRectangle duplicate (CRectangle rectparam)
{
CRectangle rectres;
rectres.width = rectparam.width*2;
rectres.height = rectparam.height*2;
return (rectres);
}