Longer discussion of this here: Why do objects of the same class have access to each other's private data?
Simple example using Line objects with an integer length. The operator+
overload function has access to the other line's private length (the parameter const Line &line
, aka the line being added to this
line). Same thing is true for a non-operator-overload function (printOtherLine
) and a friend function (printFriendLine
). Once again the Line being passed as a parameter is not this
object.
Why is this the case?
#include <iostream>
class Line
{
public:
Line()
{
length = 0;
}
Line(int length)
{
this->length = length;
}
Line operator+(const Line &line)
{
Line newLine(this->length + line.length); // I would have thought
// this would be line.getLength()
// instead of line.length
return newLine;
}
int getLength()
{
return length;
}
void printOtherLine(const Line &otherLine){
std::cout << "Other Line: " << otherLine.length << std::endl;
}
void printLine(int lineNumber){
std::cout << "Line " << lineNumber << ": " << this->length << std::endl;
}
friend void printFriendLine(const Line &friendlyLine);
private:
int length;
};
void printFriendLine(const Line &friendlyLine){
std::cout << "Friendly Line: " << friendlyLine.length << std::endl;
}
// This function will not compile
// void printUnassociatedLine(const Line &line){
// std::cout << "Unassociated Line: " << line.length << std::endl;
// }
int main()
{
Line l1(10);
l1.printLine(1);
Line l2(15);
l2.printLine(2);
Line l3 = l1 + l2;
l3.printLine(3);
Line l4(7);
l3.printOtherLine(l4);
printFriendLine(l4);
return 0;
}
Output:
Line 1: 10
Line 2: 15
Line 3: 25
Other Line: 7
Friendly Line: 7