Question

I am refreshing cpp after a long gap, trying to understand the operator overloading methods. I tried to overload "operator<<" to output members of object. but I am unable to do so without using friend function. I am looking for a method without using friend function.

here is my class def:

class Add{
private:
int x;

public:
friend ostream& operator<<(ostream& ostr, Add const& rhs); //Method 1
void operator<<(ostream& ostr);                //Method 2
};

functions implementations

//Method 1
ostream& operator<<(ostream &ostr, Add const& rhs)
{
    ostr<<rhs.x;

return ostr;
}

//Method 2
void Add::operator<<(ostream& ostr)
{
    cout<<" using operator<< \n";
    ostr<<x;
}

calls from the main function

cout<<Obj_Add;  //calls the Method 1

Obj_Add<<cout;  //calls the Method 2

Now my question is, I would like to achieve the Method 1 type calls without using the friend function. But do not know, it is possible or not in cpp. I have tried few implementation but all are gives me compile errors. Please help me to understand the point i'm missing here.

Was it helpful?

Solution

If you have public accessor functions in your class, or a stream-like one, you don't need the friendship with operator<<:

// v1
class foo{
public:
  int data() const{ return _data; }
private:
  int _data;
};

std::ostream& operator<<(std::ostream& o, foo const& f){
  return o << f.data();
}

// v2
class foo{
public:
  void stream_to(std::ostream& o){
    o << _data;
  }
private:
  int _data;
};

std::ostream& operator<<(std::ostream& o, foo const& f){
  f.stream_to(o);
  return o;
}

v2 has the added benefit of allowing stream_to to be a virtual function, which is helpful for polymorphic base-classes, so you don't need to reimplement operator<< for every derived class, only stream_to.

OTHER TIPS

It's possible with a getter of x.

if the operator<< is not friend, it can not access the member x

class Add {
    private:
        int x;

    public:
        int getX() { return x; }
};

//Method 1
ostream& operator<<(ostream &ostr, Add const& rhs)
{
    //ostr<<rhs.x;       //Fail: x is private

    ostr << rhs.getX();  //Good

    return ostr;
}

You can avoid having the operator function as friend if you have some other means of getting x from the object.

class Foo
{
private:
    int bar;

public:
    int get_bar() const { return bar; }
};

ostream &operator<<(ostream &os, const Foo &foo)
{
    os << foo.get_bar();
    return os;
}

This is not possible unless you add some mechanism to get x out, e.g. a public

// in the class
int get_x() const { return x; }

or a different mechanism to print an object

// outside the class
std::ostream &operator<<(std::ostream &out, Add const &obj)
{
    obj.print(out);
    return out;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top