Doubt about operator overloading << as a friend function

Hey guys!

I have a small doubt regarding the overloading of the << operator for a simple class as a friend function. Consider the example below:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Something
{
private:
    int x,y;

public:
    Something(int x, int y) : x(x), y(y) {}

int getX() {return x;}
int getY() {return y;}

friend std::ostream& operator<< (std::ostream &out, const Something &s);
};


Now in my definition for the overloaded << function, I noticed that using the access functions to get the x and y values and display them works (s.getX()). However since this is a friend function doing s.x also works.

What I want to know is what is better to do in such a situation. Which is more efficient? I'd guess direct access of member variables since the other one would have an extra function call?

Thanks in advance.
The compile may inline the accessor methods making them about the same. If this class is used extensively (as would be for graphics or something), I would probably use the friend function and direct access to its members. Otherwise (read as: in most cases), I would just use it's public interface and not require the friend declaration.
The idea of making it friend is that you don't need to provide the class with unnecessary accessors.
Considerer it part of the interface
Topic archived. No new replies allowed.